Google地图:事件监听器只记住变量的最终值

我正在整理一张谷歌地图,其中包含我国各地各种考试中心的位置。 它在每个县上绘制一个标记,当您单击县标记时,它会放大并概述该县的测试中心。 我也在使用jQuery。

这是问题所在:

当我绘制县标记并点击它们时,它总是缩放到最后一个县。 我用来绘制县的代码如下:

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始终是最终县的价值。 我已经尝试将key作为变量传递给函数,但它只是等于当前map poisition的经度和纬度。

也许我在做一些愚蠢的事情? 这不会是第一次:)任何帮助将非常感激。

干杯,我将事件处理程序更改为以下内容并且它有效:

 GEvent.addListener(marker, "click", (function(key) { return function() { // Zoom to county showCounty(key); }; })(key) );