Tuesday, 2 August 2011

Long - Lat - Address

How to fetch the Longitude, Latitude and Address of your current location? Let's do it:

LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), true);
Location locations = locationManager.getLastKnownLocation(provider);
List<String>  providerList = locationManager.getAllProviders();
if(null!=locations && null!=providerList && providerList.size()>0){                   
double longitude = locations.getLongitude();
double latitude = locations.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());                   
try {
    List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
        String _Location = listAddresses.get(0).getAddressLine(1);
} catch (IOException e) {

Note: Add these permissions to your manifest file: 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 Use this for network-based location.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
 Use this for GPS based location but it includes network-based location property too.
You should use both for more versatile application.

No comments:

Post a Comment