creating markers in loop - Infowindow does not open when inside an click Listener

佐手、 提交于 2019-12-01 23:57:57

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.

I have the same issue and it has got something to do with the loop, because when I use hard coded values like this they do work:

                // Add infowindow
                google.maps.event.addListener(markers[0], 'click', function() {
                  infowindows[0].open(map,markers[0]);
                });
                // Add infowindow
                google.maps.event.addListener(markers[1], 'click', function() {
                  infowindows[1].open(map,markers[1]);
                });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!