我在地理编码器外有一个数组,但当我想在地理编码器内使用该数组时,该数组的值是未定义的
var titles = new Array(<?php echo implode(",",$titles); ?>);
var length = postCode.length;
for (var i = 0; i < length; i++)
{
geocoder.geocode({'address': postCode[i]}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
lat2 = results[0].geometry.location.lat();
lng2 = results[0].geometry.location.lng();
var Latlng = new google.maps.LatLng(lat2, lng2);
var marker = new google.maps.Marker({
position: Latlng,
map: map,
title: titles[i],
icon: icon});
// alert(titles[i]) - all undefined
}
}
}
您可以直接执行
var titles = <?php echo json_encode($titles); ?>;
地理编码器是异步的。循环遍历i的所有可能值,使i设置为postCode.length+1,这是未定义的。这可以通过功能关闭来解决(但是,根据您的位置数量,您可能会遇到配额或费率限制问题):
function geocodeAddress(index) {
geocoder.geocode({'address': postCode[index]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat2 = results[0].geometry.location.lat();
var lng2 = results[0].geometry.location.lng();
var Latlng = new google.maps.LatLng(lat2, lng2);
var marker = new google.maps.Marker({
position: Latlng,
map: map,
title: titles[index],
icon: icon
});
} else { alert("geocode failed:"+status);
});
}
for(var i = 0; i < length; i++)
{
geocodeAddress(i);
}