Search code examples
androidgoogle-geocoder

How to find Latitude and Longitude from Address


I am using Address to get Latitude and Longitude of that location, but it always returns null...

I am passing address like this: 1701 Amphitheatre Pkwy Mountain View CA 94043

Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {                                                
    List<Address> addresses = geocoder.getFromLocationName(strNewClientCompleteAddress, 1);
    if ((addresses != null) && (addresses.size() > 0)) {
        Address fetchedAddress = addresses.get(0);
        lat = fetchedAddress.getLatitude();
        lng = fetchedAddress.getLongitude();
        Log.v("try-if", "ok great work");
    } else {
        Log.v("try-else", "something wrong");
    }
} catch (IOException e) {
    e.printStackTrace();
    Log.v("catch", "Could not get address....!");
}                           
strLat = String.valueOf(lat);
Log.v("lat:", strLat);
strLng = String.valueOf(lng);
Log.v("lng:", strLng);

and Log says

V/strNewClientCompleteAddress:(1466): 1701 Amphitheatre Pkwy Mountain View CA 94043
V/try-else(1466): something wrong
V/lat:(1466): 0.0
V/lng:(1466): 0.0

Manifest permissions:

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

Solution

  • I checked your code, there nothing is wrong in code.

    I got below log.

    02-21 06:21:16.036: V/try-if(18306): ok great work
    02-21 06:21:16.036: V/lat:(18306): 37.4235981
    02-21 06:21:16.036: V/lng:(18306): -122.0871014
    

    Please make sure you have import below class.

    import android.location.Address;
    import android.location.Geocoder;
    

    The Geocoder class backend is only present on Google-approved devices. So the lookup will basically fail on any device that doesn't have GMail/Market/Maps on it.

    Also check is internet is working in device..

    Note : Sometime Geocoder service is not working in background because its killed due to less memory or task manager. It will start again after reboot device.