谷歌地图API - geocode()方法没有返回纬度和经度

10

我正在尝试使用以下代码通过地址获取经度和纬度:

 function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    geocoder = new google.maps.Geocoder();
    var address = "HaYarkon 100 TelAviv Israel";
    geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK)
       {
            TelAviv = new google.maps.LatLng(results[0].geometry.location.latitude,results[0].geometry.location.longitude);             
       }
    });

    var myOptions = {
        zoom:7,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: TelAviv
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);
}

问题在于 results[0].geometry.location.latitude 和 longitude 没有定义。

在控制台中看到的结果如下:

 location: O

   $a: 51.5414691

   ab: -0.11492010000006303

为什么它显示的是$a和ab而不是纬度和经度

2个回答

21

使用以下函数而不是直接访问属性:

results[0].geometry.location.lat()

并且

results[0].geometry.location.lng()

谷歌代码是混淆的,内部使用短变量名,这些变量名可能会从一天到另一天发生改变。


2
在你的例子中,你不需要创建一个新的 google.maps.LatLngresults[0].geometry.location 就是 一个 google.maps.LatLng - Sean Mickey
@Sean Mickey,也许你能帮忙解决另一个问题,我无法将那些数据保存到脚本中的变量中。我该如何保存并使用它? - Alon
@Alon 你所需做的就是创建一个 var 并将其赋值为 results[0].geometry.location。如果你想在脚本的其他地方访问该值,你必须将其分配给具有回调函数之外范围的变量,因为 results[0](及其成员)仅在回调函数内有效。 - Sean Mickey
这是有道理的,因为lat和lng是返回对象中的函数。我遇到了同样的问题,这是我找到的唯一解决方案。谢谢! - FNunez

1

您必须使用

results[0].geometry.location.lat()
results[0].geometry.location.lng()

使用

results[0].geometry.location[0]
results[0].geometry.location[1]

返回未定义。

这让我非常困惑,因为API有时返回名为“ab”的字段,而其他时候则返回“Za”。通过语义值(使用.lat和.lng)访问元素比准确的字符串名称更安全且更易读。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接