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

后端 未结 2 1303
被撕碎了的回忆
被撕碎了的回忆 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 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.

提交回复
热议问题