gpt4 book ai didi

javascript - Google Maps API,通过循环创建带有信息窗口的多个标记的问题

转载 作者:行者123 更新时间:2023-11-30 10:56:01 24 4
gpt4 key购买 nike

我在使用以下代码时遇到的问题是,信息窗口仅在最后一个迭代标记上弹出,即使当我单击第一个标记时,最后一个标记上的信息窗口也会打开?

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

});

最佳答案

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

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

关于javascript - Google Maps API,通过循环创建带有信息窗口的多个标记的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1593335/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com