谷歌地图自动填充:如何获得lat/lng?

Sta*_*bie 32 google-maps google-maps-api-3

我正在使用Google地图的自动填充功能进行地理编码.它似乎返回了很多数据,但不是lat/lng.有没有办法获得这些信息?我想将它传回我的后端应用程序进行进一步处理.

Bre*_*ata 48

在几何对象的原型中存在称为lat()和lng()的方法.因此,要获取值,只需使用以下内容:

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!');
Run Code Online (Sandbox Code Playgroud)


Tin*_*ehr 29

好的,我不熟悉地方或自动填充.但看起来你正在寻找的是

autocomplete.getPlace().geometry.location
Run Code Online (Sandbox Code Playgroud)

为了演示我采用这个例子并添加上面的行来创建这个JSFiddle,你可以输入地名,当它被选中时,创建一个带有LatLng的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);
Run Code Online (Sandbox Code Playgroud)

  • 实际上它是@neoplomero,有了`autocomplete.getPlace().geometry.location`你可以访问`autocomplete.getPlace().geometry.location.lat()`和`autocomplete.getPlace().geometry.location.lng( )` (8认同)

Qui*_*ger 21

其他答案缺少一个关键组件。您需要'geometry'在调用setFields. 请注意,更多的字段可能会花费更多。

前任:

// 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']);
Run Code Online (Sandbox Code Playgroud)

查看文档