Google maps infowindow showing on wrong marker

后端 未结 5 537
失恋的感觉
失恋的感觉 2020-12-30 02:40

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 goo         


        
5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-30 03:03

    As a new option that was not available 7 years ago:

    all modern browsers (which is all browsers supporting ECMAScript 6) support block scoped variables which are defined using the let statement. let initializes a variable inside of a given scope e.g. inside of a loop whereas var defines variables on global or function level. In your case exchanging the var with let will make sure that each marker is properly initialized as a new variable:

    for (var i = 0; i < 8; i++) {
        let 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',
        });
        let infowindow = new google.maps.InfoWindow({
            content: 'test string'
        });
        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map,marker);
        });
    }
    

提交回复
热议问题