Javascript 谷歌地图:事件监听器只记住变量的最终值
我正在整理一张谷歌地图,其中包含了我国各地各个考试中心的位置。它在每个县上绘制一个标记,当您单击该县标记时,它将放大并提供该县考试中心的概览。我还将jQuery与此结合使用 问题是: 当我绘制县标记并单击它们时,它总是缩放到最后一个县。我用于绘制县的代码如下所示:Javascript 谷歌地图:事件监听器只记住变量的最终值,javascript,jquery,google-maps,event-listener,Javascript,Jquery,Google Maps,Event Listener,我正在整理一张谷歌地图,其中包含了我国各地各个考试中心的位置。它在每个县上绘制一个标记,当您单击该县标记时,它将放大并提供该县考试中心的概览。我还将jQuery与此结合使用 问题是: 当我绘制县标记并单击它们时,它总是缩放到最后一个县。我用于绘制县的代码如下所示: function plotCountyMarkers(county_count) { // Setup a new icon var icon = new GIcon(); var count = 0;
function plotCountyMarkers(county_count)
{
// Setup a new icon
var icon = new GIcon();
var count = 0;
// Get the type of icon to display
var centre_type = checkCentreType();
if (centre_type == 'dtc')
icon.image = dtc_icon;
else
icon.image = ctc_icon;
// Other settings including icon shadow
icon.shadow = icon_shadow;
icon.iconSize = new GSize(20, 29);
icon.shadowSize = new GSize(38, 29);
icon.iconAnchor = new GPoint(10, 29);
icon.infoWindowAnchor = new GPoint(10, 1);
// Get the total number of counties to map
var count = county_count.length;
for (key in county_count) {
// Set the LatLong of the county
var countyLocation = new GLatLng(county_locations[key][0],county_locations[key][1]);
// Set the title text of the marker
var centre_text = county_count[key]==1 ? 'Centre' : 'Centres';
var title = county_locations[key][2]+': '+county_count[key]+' Test '+centre_text;
// Add an event listener to the marker
var marker = new GMarker(countyLocation,{icon: icon, title: title});
GEvent.addListener(marker, "click", function() {
// Zoom to county
showCounty(key);
});
// Add the marker to the map
map.addOverlay(marker);
}
}
我基本上使用完全相同的方法将HTML传递到事件监听器中,当您单击县级标记时,效果很好。由于某些原因,键
始终是最终县的值。我尝试将key
作为变量传递给函数,但它只是变为等于当前地图位置的经度和纬度
也许我在做些傻事?这已经不是第一次了:)任何帮助都将不胜感激。干杯,我将事件处理程序更改为以下内容,它成功了:
GEvent.addListener(marker, "click",
(function(key) {
return function() {
// Zoom to county
showCounty(key);
};
})(key)
);
另请参见,在迭代县计数时,对使用
,而不是对
中的..使用。很好!你真的读过我贴的一些链接,是吗?