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?

- 1,452
- 2
- 14
- 17
-
Use Geocoder. Refer: http://developer.android.com/reference/android/location/Geocoder.html – shyam Sep 19 '14 at 08:06
-
Current API doesn't allow to do it with one request as it's possible with Web API. Please upvote https://issuetracker.google.com/issues/35828699 to request coordinates exposed in the predictions response. – AlexKorovyansky Feb 01 '18 at 07:32
-
this is the proper solution https://stackoverflow.com/a/70751725/6236752 – Nouman Ch Jan 18 '22 at 07:30
12 Answers
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

- 7,933
- 3
- 54
- 57

- 807
- 7
- 13
-
what exactly is the placeId? the address that user entered in the autocomplete textview? – Choy Feb 23 '19 at 09:51
-
1@Choy [place id](https://developers.google.com/places/place-id), a hash string – lasec0203 Apr 17 '20 at 05:07
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.

- 8,328
- 7
- 59
- 74
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();

- 141
- 1
- 7
-
-
1this is how you can do it in Kotlin. val fields = ArrayList
() fields.add(Place.Field.NAME) fields.add(Place.Field.ADDRESS) fields.add(Place.Field.LAT_LNG) startActivityForResult(Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY, fields).build(mContext), AUTOCOMPLETE_REQUEST_CODE); – Sadda Hussain Aug 07 '20 at 05:43
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.

- 1,699
- 1
- 10
- 14
Based on the latest version of AutoComplete documentation
Option 1: Embed an AutocompleteSupportFragment
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
autocompleteFragment
.setPlaceFields(Arrays.asList(Place.Field.ID,
Place.Field.NAME,Place.Field.LAT_LNG,Place.Field.ADDRESS));
Option 2: Use an intent to launch the autocomplete activity
List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME,Place.Field.LAT_LNG,Place.Field.ADDRESS);
// Start the autocomplete intent.
Intent intent = new Autocomplete.IntentBuilder(
AutocompleteActivityMode.FULLSCREEN, fields)
.build(this);
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
whichever fields you are interested in, you have to mention as mentioned above.
You'll get result as below:
onPlaceSelected:
{
"a":"#90, 1st Floor, Balaji Complex, Kuvempu Main Road, Kempapura, Hebbal
Kempapura, Bengaluru, Karnataka 560024, India",
"b":[],
"c":"ChIJzxEsY4QXrjsRQiF5LWRnVoc",
"d":{"latitude":13.0498176,"longitude":77.600347},
"e":"CRAWLINK Networks Pvt. Ltd."
}
Note: The result displayed is by parsing the Place object to json

- 539
- 4
- 12
add these line under function
autocomplete.addListener('place_changed', function() {});
var place = autocomplete.getPlace();
autocomplete.setFields(['place_id', 'geometry', 'name', 'formatted_address']);
var lng = place.geometry.location.lng();
var lat = place.geometry.location.lat();
var latlng = {lat , lng};
console.log(latlng);

- 1,149
- 2
- 15
- 22

- 85
- 2
- 5
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Constant.REQUEST_LOCATION_CODE) {
Place place = PlaceAutocomplete.getPlace(this, data);
if (place != null) {
LatLng latLng = place.getLatLng();
mStringLatitude = String.valueOf(latLng.latitude);
mStringLongitude = String.valueOf(latLng.longitude);
EditTextAddress.setText(place.getAddress());
}
}
}
With the code above, you can get the LatLng as well as the String address. Use the LatLng wherever you want.

- 9,564
- 146
- 81
- 122

- 599
- 5
- 18
Geocoding is a very indirect solution, and like the second responder said, if you do "Apple Store" it may not return the full address. Instead:
Place_ID contains everything you need. I am assuming you know how to get the place_id from the Places API (they have a full example if not).
Then pull a second request for the place details (including latitude and longitude under the geometry section) using the place_id following this documentation: https://developers.google.com/places/documentation/details?utm_source=welovemapsdevelopers&utm_campaign=mdr-devdocs

- 21
- 2
Ref :- https://developers.google.com/places/android/place-details#get-place The above link gives a place object which will have lat and long . The place object is deirved from placeid that one gets from place autocomplete.

- 379
- 3
- 15
This snippet allows obtain the latitude and longitude of a place according to the identifier back into the auto complete
public class PlacesDetails {
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String TYPE_DETAIL = "/details";
private static final String OUT_JSON = "/json";
//private static final String API_KEY = "------------ make your specific key ------------; // cle pour le serveur
public PlacesDetails() {
// TODO Auto-generated constructor stub
}
public ArrayList < Double > placeDetail(String input) {
ArrayList < Double > resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_DETAIL + OUT_JSON);
sb.append("?placeid=" + URLEncoder.encode(input, "utf8"));
sb.append("&key=" + API_KEY);
URL url = new URL(sb.toString());
//Log.e("url", url.toString());
System.out.println("URL: " + url);
System.out.println("******************************* connexion au serveur *****************************************");
//Log.e("nous sommes entrai de test la connexion au serveur", "test to connect to the api");
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in .read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
System.out.println("le json result" + jsonResults.toString());
} catch (MalformedURLException e) {
//Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
//Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
System.out.println("******************************* fin de la connexion*************************************************");
}
try {
// Create a JSON object hierarchy from the results
//Log.e("creation du fichier Json", "creation du fichier Json");
System.out.println("fabrication du Json Objet");
JSONObject jsonObj = new JSONObject(jsonResults.toString());
//JSONArray predsJsonArray = jsonObj.getJSONArray("html_attributions");
JSONObject result = jsonObj.getJSONObject("result").getJSONObject("geometry").getJSONObject("location");
System.out.println("la chaine Json " + result);
Double longitude = result.getDouble("lng");
Double latitude = result.getDouble("lat");
System.out.println("longitude et latitude " + longitude + latitude);
resultList = new ArrayList < Double > (result.length());
resultList.add(result.getDouble("lng"));
resultList.add(result.getDouble("lat"));
System.out.println("les latitude dans le table" + resultList);
} catch (JSONException e) {
///Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
PlacesDetails pl = new PlacesDetails();
ArrayList < Double > list = new ArrayList < Double > ();
list = pl.placeDetail("ChIJbf7h4osSYRARi8SBR0Sh2pI");
System.out.println("resultat de la requette" + list.toString());
}
}

- 5,987
- 8
- 76
- 112

- 31
- 3
-
I think you should add that this should be run in an async thread. – Taslim Oseni Sep 28 '20 at 08:48
I got very simple solution to this problem thanks answer by Muhammad Yasir.
List<Place.Field> placeFields = Arrays.asList(Place.Field.LAT_LNG, Place.Field.ADDRESS_COMPONENTS);
autocompleteFragment.setPlaceFields(placeFields);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
LatLng latLng = place.getLatLng(); // This will have required latitude and longitude
}
}
You can specify any field you want as in the list like name, address etc.
Note: This answer is for android java but I think there will be similar approach in other languages like javascript.

- 73
- 1
- 6
Places.GeoDataApi.getPlaceById(mGoogleApiClient, placeId)
.setResultCallback(new ResultCallback < PlaceBuffer > () {
@Override
public void onResult(PlaceBuffer places) {
if (places.getStatus().isSuccess() && places.getCount() > 0) {
final Place myPlace = places.get(0);
Log.i(TAG, "Place found: " + myPlace.getName());
LatLng latlangObj = myPlace.getLatLng();
Log.v("latitude:", "" + latlangObj.latitude);
Log.v("longitude:", "" + latlangObj.longitude);
} else {
Log.e(TAG, "Place not found");
}
places.release();
}
});
Use this method for getting lat and lang from placeid.

- 5,987
- 8
- 76
- 112

- 77
- 1
- 4