get Lat Lang from a place_id returned by autocomplete place api

I am searching the place in my apps using the google autocomplete place api and now I want to get latitude and longitude of the place that i have searched. How to get latitude and longitude from the result returned by autocomplete place api by google in android?


Solution 1:

The following code snippet which uses Google Places API for android worked for me

Places.GeoDataApi.getPlaceById(mGoogleApiClient, placeId)
    .setResultCallback(new ResultCallback<PlaceBuffer>() {
  @Override
  public void onResult(PlaceBuffer places) {
    if (places.getStatus().isSuccess()) {
      final Place myPlace = places.get(0);
      LatLng queriedLocation = myPlace.getLatLng();
      Log.v("Latitude is", "" + queriedLocation.latitude);
      Log.v("Longitude is", "" + queriedLocation.longitude);
    }
    places.release();
  }
});

Visit Google Places API for Android for a full list of methods to retrieve data from a place

Solution 2:

Google Place Details is the answer.

From the place_id you got, query Place Details something like https://maps.googleapis.com/maps/api/place/details/json?placeid={placeid}&key={key} and you can get the lat and lng from result.geometry.location JSON.

Solution 3:

do provide Place.Field.LAT_LNG to get the latitude and longitude for the place.

 autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, 
 Place.Field.NAME,Place.Field.LAT_LNG));

then get LatLng

LatLng destinationLatLng = place.getLatLng();

and can see through toast

 destlat = destinationLatLng.latitude;
 destLon = destinationLatLng.longitude;
 Toast.makeText(getApplicationContext(), "" + destlat + ',' + destLon, Toast.LENGTH_LONG).show();

Solution 4:

Each place returned in the place-autocomplete response has an Id and a reference string as explained here.

Use either (preferably Id since reference is deprecated) to query Places API for the full information about that place (including lat/lng): https://developers.google.com/places/documentation/details#PlaceDetailsRequests

Regarding shyam's comment - Geocoding will work only if you got a full address in the autocomplete response which is not always the case. Also Geocoding gives a list of possible results since the place description you get in the autocomplete response is not unique. Depending on your needs, geocoding might be enough.