Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps Autocomplete: how to get lat/lng?

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.

like image 919
StackOverflowNewbie Avatar asked Jun 09 '12 01:06

StackOverflowNewbie


People also ask

How do I get latitude and longitude on Google Autocomplete API?

You could use place. geometry. location. lat() and place.

How do you find the longitude and latitude from autocomplete without showing the map?

You can use the Google API to get the Longitude and Latitude from your address. As you already said, you should implement a hidden field where the result should be inserted. Then you can save the location together with the coordinates. Save this answer.


2 Answers

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!'); 
like image 133
Brent Barbata Avatar answered Sep 17 '22 17:09

Brent Barbata


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); 
like image 44
Tina CG Hoehr Avatar answered Sep 17 '22 17:09

Tina CG Hoehr