我在地图上显示多个标记时遇到问题。该代码首先循环遍历一个数组,然后对纬度、经度值进行反向地理编码,然后显示标记并将 infoWindow 的内容设置为返回的地址。
我的代码如下。
for(var i=0; i < useNowArray.length; i++) {
// plot useNow on map
latlng = new google.maps.LatLng(useNowArray[i]['lat'], useNowArray[i]['lon']);
console.log(useNowArray[i]['lat'] + useNowArray[i]['lon']);
geocoder.geocode({'latLng': latlng}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
if (results[0])
{
marker = new google.maps.Marker({
position: latlng,
map: map,
icon: 'http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png',
title: results[0].formatted_address
});
content = results[0].formatted_address;
console.log(content);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(content);
infowindow.open(map, this);
}
})(marker, i));
}
} else {
alert("Geocoder failed due to: " + status);
}
}); // end geocode function
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
问题是只显示我的最后一个标记。
我缺少什么? :(
非常感谢。
您的标记变量是全局的,地理编码是异步的。循环执行,触发 useNowArray.length 请求,每个请求都会使用结果位置更新全局标记。循环完成后,标记将保留在循环中的最后一个位置。类似问题及其解决方案:
- Google Maps API v3 - 多次地理编码器请求后的 fitBounds https://stackoverflow.com/questions/11336405/google-maps-api-v3-fitbounds-after-multiple-geocoder-requests
- 多个标记的问题(Google Maps API v3) https://stackoverflow.com/questions/4266377/problem-with-multiple-markers-google-maps-api-v3
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)