2012-05-07 48 views
10

我试图通过地址用下面的代码来获得纬度和经度:谷歌地图API - 地理编码()不返回lat和长

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]。几何位置,海拔和经度都未知。

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

location: O 

    $a: 51.5414691 

    ab: -0.11492010000006303 

为什么它显示$ a和的直接访问AB代替纬度和经度

回答

19

使用下面的功能,而不是属性:

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

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

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

+0

非常好,thx! – Alon

+2

而在你的例子中,你不必创建一个新的'google.maps.LatLng'; 'results [0] .geometry.location'_is_a google.maps.LatLng'。 –

+0

@Sean Mickey,也许你可以帮助解决另一个问题,我似乎无法将该数据保存到脚本中的变量中。我如何保存并使用它? – Alon

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)访问元素而不是确切的字符串名称更安全,更具可读性。