Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google maps infowindow showing on wrong marker

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?

like image 507
PeanutButterJelly Avatar asked Apr 20 '11 21:04

PeanutButterJelly


People also ask

How do I edit InfoWindow on Google Maps?

You can modify the whole InfoWindow using jquery alone... var popup = new google. maps. InfoWindow({ content:'<p id="hook">Hello World!

How do I get rid of InfoWindow in Google Maps?

After constructing an InfoWindow, you must call open to display it on the map. The user can click the close button on the InfoWindow to remove it from the map, or the developer can call close() for the same effect.

How do I put InfoWindow on marker?

Call setPosition() on the info window, or. Attach the info window to a new marker using the InfoWindow. open() method. Note: If you call open() without passing a marker, the InfoWindow will use the position specified upon construction through the InfoWindowOptions object literal.


2 Answers

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);
    });
}
like image 63
Herman Schaaf Avatar answered Sep 23 '22 12:09

Herman Schaaf


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.

like image 40
André Luiz Avatar answered Sep 22 '22 12:09

André Luiz