谷歌地图:事件监听器仅记住变量的最终值

2023-12-01

我正在整理一张 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作为函数的变量,但它只是等于当前地图位置的经度和纬度。

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


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

GEvent.addListener(marker, "click",
    (function(key) {
        return function() {
            // Zoom to county
            showCounty(key);
        };
    })(key)
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

谷歌地图:事件监听器仅记住变量的最终值 的相关文章

随机推荐