【发布时间】:2016-09-18 08:52:24
【问题描述】:
我正在使用地理编码 API 将地址转换为纬度和经度坐标值。我确实收到了结果,但 lat 和 long 为空。其他 SO 帖子提到地理编码器请求是异步的,谷歌只是没有足够快地返回数据。如果这是问题,我不明白如何为我的代码解决这个问题。
var coords = [];
var address = '1600 Pennsylvania Ave NW, Washington, DC 20500';
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function( results, status ) {
if (status === google.maps.GeocoderStatus.OK) {
coords[0] = results[0].geometry.location.lat();
coords[1] = results[0].geometry.location.lng();
}
else {
coords = 'Could not retrieve coordinates for: ' + address;
}
});
return coords;
即使我使用众所周知的地址,我仍然没有经纬度。
结果对象:
这真的是问题还是我使用的代码有问题?我该如何解决这个问题?
【问题讨论】:
-
你不能从异步回调函数中返回任何东西,你需要在数据存在的时候/在哪里使用那里的数据
-
那么这个文档的意义是什么:developers.google.com/maps/documentation/javascript/geocoding 它提到了返回的所有内容,包括几何:{location: LatLng}...这是我需要的。
-
相关/可能重复的问题:Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference。 lat/lng 被返回(如果结果为“OK”),它们只是在回调函数中返回
coords的值返回给调用者功能。 -
很好的链接,但这就是我所指的。听起来这可能是一个异步问题,但我不明白如何解决这个问题。将结果传递给另一个函数如何让 Google 有更多时间响应请求的完整信息?我无法想象我是唯一遇到过这个问题的开发人员。网上没有关于可能修复的示例的信息。
-
一个选项(在链接的问题中描述)是一个承诺。
标签: javascript google-maps google-geocoder google-geocoding-api