问题
I am having a problem with displaying multiple markers on my map. The code starts by looping through an array, and then reverse geocoding the lat, lon values before displaying a marker and setting the content of the infoWindow to the returned address.
My codes are below.
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);
The issue is that only my last marker is shown.
What am i missing? :(
many thanks.
回答1:
Your marker variable is global, geocoding is asynchronous. The loop executes, firing off useNowArray.length requests, each one updates the global marker with the resulting position. When the loop is done, the marker is left at the last location in the loop. Similar questions with solutions to the issue:
- Google Maps API v3 - fitBounds after multiple geocoder requests
- Problem with multiple markers (Google Maps API v3 )
来源:https://stackoverflow.com/questions/13463760/multiple-markers-on-google-map-only-last-marker-is-shown