Google Maps API,通过循环创建带有infowindows的多个标记的问题

时间:2009-10-20 09:02:33

标签: javascript google-maps

我在下面的代码中遇到的问题是信息窗口只会弹出最后一个迭代标记,即使我点击第一个标记打开了最后一个标记上的信息窗口?

$(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);
    }

});

1 个答案:

答案 0 :(得分:4)

这是因为循环没有作用域,因此标记将是循环中创建的最新标记。您必须将循环内容包装在函数中:

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