0

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 content = '<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;
        });
    }
4
  • can you fix the indenting? its quite confusing. Commented Jun 29, 2011 at 20:24
  • 1
    Where's the closing } of your for loop? Commented Jun 29, 2011 at 20:24
  • Are you missing the closing brace for the for? Commented Jun 29, 2011 at 20:26
  • @Dogbert and @Daniel A. White my code it's already modified Commented Jun 29, 2011 at 20:26

2 Answers 2

3
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));
Sign up to request clarification or add additional context in comments.

1 Comment

awesome men!! i didn't know that i'm going to read a little bit more of javascript work
0

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>'
});

1 Comment

sure, that was my first solution but with the same result

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.