javascript - 谷歌地图 : Event Listener only remembering final value of variable

标签 javascript jquery google-maps event-listener

我正在整理一张 Google map ,其中包含我国各地各个考试中心的位置。它在每个县上绘制一个标记,当您单击县标记时,它会放大并提供该县考试中心的概述。我也在使用 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 位置的经度和纬度。

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

最佳答案

干杯,我将事件处理程序更改为以下内容并且它起作用了:

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

关于javascript - 谷歌地图 : Event Listener only remembering final value of variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1841247/

相关文章:

javascript - 使用 JavaScript 检查 Canvas 上的两个项目是否重叠

javascript - 使用 JavaScript 在文本鼠标悬停时显示不同的弹出图像

带有数组的javascript正则表达式模式

php - xmlHttp 字符串 POST header 问题

javascript - 在 PHP 和 Mysql 的 jquery 日期选择器中禁用给定范围内的日期

javascript - 是否可以将图像放置在屏幕中央而不是浏览器中央?

javascript - 使复选框在可复制的输入字段中充当单选按钮

google-maps - 新的谷歌地图嵌入选项

java - 保存 Google map 的部分内容

javascript - 如何设置 google Map.Place.AutoComplete 结果的样式?