How do you rate this blog

Tuesday, August 7, 2012

To get Latitude and Longitude of Current Location


This post explains how to get the current location using GPS. In this post the app will display your current latitude and longitude if it can access the network.

The logic for this is -
1)      Provide the app access to GPS in the device.
2)      Get location manager, which enables the device to get periodic location updates of the device.
3)      Then select the best provider based on the criteria.
4)      Then obtain the latitude and longitude if there is a provider.

Based on the logic mentioned above lets code the application –

1)      In the android manifest file provide access to the GPS using code as shown in the snapshot given below.

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

The code will look as shown below in the snapshot



2)      Get the location manager – 

LocationManager LC=(LocationManager) getSystemService(Context.LOCATION_SERVICE);

The above code creates a location manager to get the location updates.

3)      Select the best provider based on the criteria –
Criteria criteria=new Criteria();
provider=LC.getBestProvider(criteria, false);
        Location loc=LC.getLastKnownLocation(provider);
4)      Obtain the latitude and longitude –

@Override
        public void onLocationChanged(Location location) {
                        intlat=(int) (location.getLatitude());
                        intlon=(int) (location.getLongitude());
                        latitudeval.setText(String.valueOf(lat));
                        longitudeval.setText(String.valueOf(lon));
        }

The code will look as shown below.



Create an APK file out of it and install on your mobile and run the application. The output will be as shown in the snapshot shown below.


2 comments:

  1. Hello Programmer,
    I have tested your code but when i just execute it. It gives me No Provider.
    "Need To correct it"

    ReplyDelete
  2. Hi Amal,

    The code has been tested and the snapshots are from a working mobile, have a look into your code may be you have missed something.

    ReplyDelete