我有两个Javascript函数,试图使用Google Maps API Geocode查找地址的纬度和经度:
function getLatLon(address) {
var location = -1;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat();
var lon = results[0].geometry.location.lng();
location = new Array(lat, lon);
//document.getElementById('results').innerHTML = location[0];
} else {
alert("Geocode was not successful.");
}
});
return location;
}
function search() {
var address = document.getElementById('address').value;
var location = getLatLon(address);
document.getElementById('results').innerHTML = location[0];
}
虽然getLatLon()中的location [0]在#results div中打印出正确的数字,但search()中的location [0]返回undefined。你有什么想法可能会发生这种情况吗?我试过从getLatLon()返回一个普通的字符串(“Hello”),而且工作得很好。
答案 0 :(得分:6)
问题是geocoder.geocode(...)
异步,因此您无法返回值。请尝试这样:
function getLatLon(address, callback) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat();
var lon = results[0].geometry.location.lng();
location = new Array(lat, lon);
callback(location);
} else {
alert("Geocode was not successful.");
}
});
}
function search() {
var address = document.getElementById('address').value;
getLatLon(address, function(location) {
document.getElementById('results').innerHTML = location[0];
});
}
答案 1 :(得分:2)
根据the API docs,调用geocoder.geocode(request, callback_function)
将立即返回任何内容。收到并处理完回复后,将调用callback_function
。在此之前,location
将保留您设置的任何值。
当您致电getLatLon
时,您需要在回叫功能中启动搜索功能。为了获得灵活性,您可以通过向getLatLon
添加一个将在geocode()
回调函数中调用的回调参数来实现此目的。