i have a google map with multiple markers and each has its own infowindow.
nothing happens when i click. fyi: i know it the listener fires because i did put a alert in
It is because you probably have closure within loop! So the variable i
in callback is already overwritten at the time when the callback is called. You have two options how to fix it:
1) classical "closure in loop" workaround (you do another closure for every loop iteration):
for (i = 0; i < 20; i++) { (function (i) {
google.maps.event.addListener(point[i], 'click', function() {
infowindow[i] = new google.maps.InfoWindow({content: contentString[i] });
infowindow[i].open(map,point[i]);
});
})(i);
}
2) avoid closure and use the marker data structure:
for (i = 0; i < 20; i++) {
point[i].i = i;
google.maps.event.addListener(point[i], 'click', function() {
this.myinfowindow = new google.maps.InfoWindow({content: contentString[this.i] });
this.myinfowindow.open(map, this);
});
}
(or you could also move the contentString also to the marker: point[i].contentString = ...
and use this.contentString
in the click handler. Then you don't need the point[i].i
attribute.)
Personally I much more prefer the 2nd solution over the first, since the closures consume memory etc.