Kindly look at the following two code examples from Google Maps API:
Bad:
for (var i = 0; i < 8; i++) {
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(lat[i], lng[i]),
icon: '/static/images/iconsets/gmap/iconb' + (i+1) + '.png',
});
var infowindow = new google.maps.InfoWindow({
content: 'test string'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
Good:
for (var i = 0; i < 8; i++) {
createMarker(i);
}
function createMarker(i) {
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(lat, lng),
icon: '/static/images/iconsets/gmap/iconb' + (i+1) + '.png',
});
var infowindow = new google.maps.InfoWindow({
content: 'test string'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
The problem with the first code example is that when any marker
is clicked, the event handler will open the infowindow associated with the last marker instead of the clicked marker. According to this post, this happens because a marker is overwritten by a new marker in the loop. However, I don't understand how event listeners are correctly associated with the right markers while they open the infowindow associated with the last marker only when clicked. Could somebody elaborate what exactly is going on here?