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

后端 未结 2 1302
被撕碎了的回忆
被撕碎了的回忆 2021-01-23 02:25

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

相关标签:
2条回答
  • 2021-01-23 02:43

    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]);
                    });
    
    0 讨论(0)
  • 2021-01-23 03:03

    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.

    0 讨论(0)
提交回复
热议问题