I'm using Google Maps' autocomplete feature for geocoding. It seems to return a lot of data, but not the lat/lng. Is there a way to get this information? I'd like to pass it back to my backend application for further processing.
40
votes
possible duplicate of LatLngBounds - how to get SW and NE points
– Wouter van Nifterick
You're just firing a lot of questions (429 questions vs 15 answers) without properly describing that you want to do or what you've tried to solve it yourself. It adds noise to this website.
– Wouter van Nifterick
They aren't duplicates. One deals with trying to determine a rectangle and this one deals with the response the API returns.
– StackOverflowNewbie
Do you mean Places autocomplete? Would you provide more information, maybe some code if it's not too verbose?
– Tina CG Hoehr
I'm using this: developers.google.com/maps/documentation/javascript/…
– StackOverflowNewbie
3 Answers
60
votes
There are methods called lat() and lng() that exist on the geometry object's prototype. So to get the values, just use the following:
var place = autocomplete.getPlace();
var lat = place.geometry.location.lat(),
lng = place.geometry.location.lng();
// Then do whatever you want with them
console.log(lat);
console.log(lng);
console.warn('Warning: I didn\'t test this code!');
36
votes
OK, I'm not familiar with Places or Autocomplete. But it looks like what you are looking for is
autocomplete.getPlace().geometry.location
To demonstrate I took this example and added the line above to create this JSFiddle where you can enter the place name and when it's selected, an infowindow with the LatLng is created.
In particular it listens to the user's selection, then refreshes the infowindow.
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
var place = autocomplete.getPlace();
...
infowindow.setContent('<div><strong>' + place.name +
'</strong><br>' + address + "<br>" + place.geometry.location);
21
votes
The other answers are missing a critical component. You need to include 'geometry'
when you call setFields
. Be aware that more fields may cost more.
Ex:
// Avoid paying for data that you don't need by restricting the set of
// place fields that are returned to just the address components.
autocomplete.setFields(['address_component', 'geometry']);