Google maps infowindow showing on wrong marker
There's a very simple solution to your problem, which is to put the loop's code into a function. Your problem is that you overwrite the variable marker
, so that when it is accessed in the click event, it uses the latest version of that variable, which is the last marker you added.
So, when you put it into a function, the variable is in a separate namespace and therefore not overwritten. In other words, this should work:
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);
});
}
google.maps.event.addListener(Marker, 'click', function() {
InfoWindow.open(map, this);
});
You shoud use this instead of marker because marker will hold the value of last placed marker.