Sun
Sun

Reputation: 6888

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" />

Upvotes: 0

Views: 490

Answers (3)

Niranj Patel
Niranj Patel

Reputation: 33258

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.

Upvotes: 1

Andrew Matiuk
Andrew Matiuk

Reputation: 922

Another way is to use Google Api https://developers.google.com/places/documentation/autocomplete

directly, you will get JSON list with locations.

this approach is not dependent on Play Services on phone, but uses Maps API Key

Upvotes: 0

Christopher
Christopher

Reputation: 10279

  1. Have you set the necessary permissions, e.g.:

    android.permission.INTERNET"

  2. Have you added Google Play Services?

  3. What return Geocoder.isPresent() method? http://developer.android.com/reference/android/location/Geocoder.html#isPresent%28%29

Upvotes: 0

Related Questions