开发者

problem with instance of string var

开发者 https://www.devze.com 2023-03-16 13:13 出处:网络
I\'m doing a loop and on each iteration i\'m setting a string var called content, this var i\'m using to create some infoWindows of google map markers. But on each iteration that change the value of t

I'm doing a loop and on each iteration i'm setting a string var called content, this var i'm using to create some infoWindows of google map markers. But on each iteration that change the value of the var instead that make a new instance, this modifed the value and always sets the infoWindows of the markers with the last value of the var content why i'm doing wrong.

    for (var i = 0; i < info.length; i++) {

        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(info[i].split(',')[5],
                                        info[i].split(',')[6]),
            optimized: false,
            map: map,
            zoom: 6,
            draggable: true,
            animation: google.maps.Animation.DROP
        });


        var con开发者_高级运维tent = '<p>Central: ' + info[i].split(',')[1] + '</p>';

        var infoWindow = new google.maps.InfoWindow({
            content:  content
        });

        google.maps.event.addListener(marker, 'click', function () {
            infoWindow.open(map, this);
            currentMarker = this;
        });
    }


google.maps.event.addListener(marker, 'click', function () {
    infoWindow.open(map, this);
    currentMarker = this;
});

Is creating a closure and infoWindow points to the the outer function variable so all your handlers open the same infoWindow. There is only function scope in javascript(no one for every for, if, etc). Use a closure to achieve what you want:

google.maps.event.addListener(marker, 'click', (function(infoW){
    return function () {
        infoW.open(map, this);
        currentMarker = this;
    };
})(infoWindow));


This is indeed weird.

Did you try to make the content building inline?

var infoWindow = new google.maps.InfoWindow({
    content:  '<p>Central: ' + info[i].split(',')[1] + '</p>'
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号