Lars
Lars

Reputation: 8458

Google Maps API v3 Multiple Info Boxes not opening on click

Can somebody please explain why my Google Maps info windows are only opening at the bottom left marker? See here for the fiddle http://jsfiddle.net/Vj3nw/7/

When I click on any of the markers, only the bottom-left one is opened. I would like the marker that is clicked to open.

I believe the problem is due to the loop below, and this question seems to have the same problem Setting onclick to use current value of variable in loop

"The problem you were hitting is that javascript doesn't use block scope. Instead all variables have a lifetime of their containing function. So there was only ever one a captured in all of the onclick functions and they all see it's final value."

I just can't quite translate that solution to mine.

Many thanks.

for (var i = 0; i < 4; i++) {
    var marker = new google.maps.Marker({
        position: flightPlanCoordinates[i],
        icon: Symbol,
        map: map
    });

    infowindow = new google.maps.InfoWindow();
    infowindow.setContent("hello");

    google.maps.event.addListener(marker, 'click', function () {
        infowindow.open(map, marker);
    });

}

Upvotes: 0

Views: 233

Answers (1)

Craig Blagg
Craig Blagg

Reputation: 536

Generating your markers and adding the listeners in their own function, called from the loop like the updated fiddle works.

function create_marker(i,flightPlanCoordinates,Symbol,map){
        var marker = new google.maps.Marker({
            position: flightPlanCoordinates[i],
            icon: Symbol,
            map: map
        });

        infowindow = new google.maps.InfoWindow();
        infowindow.setContent("hello" + i);

        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map,marker);
        });
    }

Upvotes: 1

Related Questions