我已设法对多达 10 个地址进行地理编码并向地图添加标记,但我需要在地理编码 (codeAddress) 函数之外访问地理编码结果。我以为我可以将结果推送到全局变量数组(userLat,userLng)。使用警报我可以看到循环确实将结果添加到函数内的数组中,但该数组在函数之外是没有价值的。
附带说明一下,地理编码不成功的警报应返回地址“i”,具体取决于哪个地址有问题,但仅显示循环的最后一个地址值。
也许问题是相关的?我认为这可能与我对嵌套函数缺乏了解有关。
我希望这很清楚。提前感谢您的帮助!
function codeAddress() {
var useradd = [];
var geocoder = new google.maps.Geocoder();
var howmany = parseFloat(document.getElementById("howmany").value);
for (var i=0; i<howmany; i++) {
useradd[i] = document.getElementById('address['+i+']').value;
geocoder.geocode( {address: useradd[i]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
userLat.push(parseFloat(results[0].geometry.location.lat()));
userLng.push(parseFloat(results[0].geometry.location.lng()));
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
else {
alert('Address ' + i + ' was not successfully located for the following reason: ' + status);
}
});
};
}
编辑:
我不确定我是否理解正确,但已经提取了回调函数并创建了一个由地理编码器调用的新函数。但是问题仍然存在,并且变量 userLat 和 userLng 没有在循环之外进行。有什么建议么?
函数代码地址(){
function callBack() {
return function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
userLat.push(parseFloat(results[0].geometry.location.lat()));
userLng.push(parseFloat(results[0].geometry.location.lng()));
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
else {
alert('Address ' + i + ' was not successfully located for the following reason: ' + status);
}
}
}
var userLat = [];
var userLng = [];
var useradd = [];
var geocoder = new google.maps.Geocoder();
var howmany = parseFloat(document.getElementById("howmany").value);
for (var i=0; i<howmany; i++) {
useradd[i] = document.getElementById('address['+i+']').value;
geocoder.geocode({address: useradd[i]}, callBack());
};
}