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?
You can modify the whole InfoWindow using jquery alone... var popup = new google. maps. InfoWindow({ content:'<p id="hook">Hello World!
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With