views:

471

answers:

1

The problem I am having with the below code is that the info window only pops up on the last iterated marker, even when i click on the first marker the infowindow on the last marker is opened?

$(document).ready(function(){

    if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map_canvas"));
        map.addControl(new GSmallMapControl());
        map.setMapType(G_NORMAL_MAP);
        map.setCenter(new GLatLng(-29, 24), 5);

        var cIcon = new GIcon();
        cIcon.image = '/img/gmap_marker-01.png';
        cIcon.shadow = /img/gmap_marker_shadow-01.png';
        cIcon.shadowSize = new GSize(80, 25);
        cIcon.iconSize = new GSize(48, 32);
        cIcon.iconAnchor = new GPoint(23,31);
        cIcon.infoWindowAnchor = new GPoint(5, 1);
    }

var coords = {
96 : {lat: -29.11813, lon: 26.223091},
97 : {lat: -34.041023, lon: 18.444715},
98 : {lat: -29.857003, lon: 31.024794},
99 : {lat: -33.93264, lon: 25.56995},
100 : {lat: -26.201452, lon: 28.045488},
101 : {lat: -25.746019, lon: 28.18712},
142 : {lat: -33.960396, lon: 22.456244},
143 : {lat: -32.991009, lon: 27.901569},
144 : {lat: -31.89701, lon: 26.873444},
145 : {lat: -28.744031, lon: 31.889691},
146 : {lat: -27.75588, lon: 29.933845},
147 : {lat: -28.737811, lon: 24.766211},
148 : {lat: -26.870491, lon: 26.664465},
149 : {lat: -25.668498, lon: 27.242372},
150 : {lat: -25.864549, lon: 25.642374},
151 : {lat: -25.4701, lon: 30.97808},
152 : {lat: -23.912257, lon: 29.45355}
};

    markerOpts = {icon : cIcon};

    for(branchId in coords){
        var point = new GLatLng(coords[branchId]['lat'], coords[branchId]['lon']);

        var marker = new GMarker(point, markerOpts);

        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml('hello');
        });
        map.addOverlay(marker);
    }

});
+2  A: 

This is because loop hasn't a scope so marker will be the latest one created in your loop. You have to wrap your loop content in a function:

for (branchId in coords) {
    function() {
     var point = new GLatLng(coords[branchId]['lat'], coords[branchId]['lon']);

     var marker = new GMarker(point, markerOpts);

     GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml('hello');
     });
     map.addOverlay(marker);
    }(branchId)
}
eskimoblood