Google maps infowindow showing on wrong marker

PeanutButterJelly picture PeanutButterJelly · Apr 20, 2011 · Viewed 9.2k times · Source

I have a piece of javascript code where I create markers and attach InfoWindows to them, like this:

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);
    });
}

But when I click one of the markers, the infowindow always shows only on one marker. What am I doing wrong?

Answer

Herman Schaaf picture Herman Schaaf · Apr 20, 2011

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);
    });
}