Google Maps API - geocode()不会返回lat和long

时间:2012-05-07 12:12:00

标签: google-maps

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

 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);
}

问题是结果[0] .geomety.location.latitude和经度是未定的。

我在控制台的结果中看到的是下一个:

 location: O

   $a: 51.5414691

   ab: -0.11492010000006303

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

2 个答案:

答案 0 :(得分:19)

使用以下功能而不是直接访问属性:

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

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

Google代码经过混淆,内部使用的短变量名称可能会从一天变为另一天。

答案 1 :(得分:1)

你必须使用

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

使用

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

返回undefined。

这对我来说非常混乱,因为API有时会返回一个名为'ab'的字段,有时会返回'Za'。通过语义值(使用.lat和.lng)而不是精确的字符串名称访问元素更安全,更易读。

相关问题