我正在尝试使用谷歌地图地理编码将此地址字符串转换为 LatLng 对象。我相信因为它是一个异步调用,所以 latlng 被分配为 null。我该怎么做才能使变量赋值按照我想要的方式工作?
var latlng = codeAddress(address)
alert("Lat/lng is: " + latlng);
function codeAddress(address) {
geocoder.geocode( {'address':address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
return results[0].geometry.location;
} else {
alert("Geocode failed due to: " + status);
}
});
}
最佳答案
由于 geocode()
是异步的,正如您也提到的,无法同步调用它。因此,var latlng = codeAddress(address);
不可能。您需要在函数本身内部使用地理编码的结果。考虑:
var latlng = null;
function codeAddress(address) {
geocoder.geocode( {'address':address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latlng = results[0].geometry.location; // use latlng here ..., e.g.:
alert("Lat/lng is: " + latlng);
} else {
alert("Geocode failed due to: " + status);
}
});
}
调用 codeAddress(address)
分配给全局变量 latlng
。但是,问题是您不知道分配何时发生。在上述情况下,您只有在出现警告框后才能知道。
一般的方法是在回调中处理地理编码的结果,例如使用结果填充 HTML 字段。
关于javascript - 如何将此地理编码请求分配给变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8118431/