Google Maps事件监听器在Javascript中不能正常工作'for'循环

Google Maps event listeners not working properly in a Javascript 'for' loop

本文关键字:工作 循环 for 常工作 监听器 事件 Maps Javascript 不能 Google      更新时间:2023-09-26

我试图建立一个谷歌地图实例,其中一些内容是动态生成的一组点。

现在,我正在使用for循环来遍历任意数量的纬度和经度值,并在地图上创建标记。

我正在尝试添加与这些标记对应的信息窗口,并在单击标记时弹出它们。

然而,我遇到了一点麻烦。它看起来像我的for循环,创建基本上所有的工作都没有失败,除了eventListener部分:

function drawMap(points) {
    popUps = new Array();
    infoWindows = new Array();
    positions = new Array();
    contents = '<div id = "content">' +
        '<div id="siteNotice">' +
        '</div>' +
        '<p id="firstHeading" class="firstHeading">Position</h1>' +
        '</div>';
    infowindow = new google.maps.InfoWindow({
        content: contents
    });
    for( i = 0; i < points.length; i++ ){
        positions[i] = new google.maps.Marker({ position: 
        latlng[i], 
        map:map, 
        title:"Position"});
        popUps[i] = '<div id = "content">' +
            '<div id="siteNotice">' +
            '</div>' +
            '<p id="firstHeading" class="firstHeading">Position</h1>' +
            '</div>';
        infoWindows[i] = new google.maps.InfoWindow({
            content: popUps[i]
        });
    // everything up to this point works fine, I can reference it all manually
    // and get back the expected value.
        google.maps.event.addListener(positions[i], 'click', function(){
            infoWindows[i].open(map, positions[i]);                 
        });
    // if I change each instance of "i" to "0" here, I'll get a popup on the
    // expected marker containing content that I defined in this for loop. Same for
    //  "1" and "2." But "i" doesn't work.
    }
}

其中"map"是google.maps.Map的一个实例,每个弹出窗口的实例在最终产品中会有所不同。

我在页面加载时调用这个函数,它将位置和标记添加到我的地图中:

drawMap([[13.283 , 162.232], [18.232 , 112.223], [17.233, 80.293]]);

有人知道为什么我不能动态地创建eventListeners吗?任何帮助将非常感激!

提前感谢。:)

编辑:

结果是,这里的要求只是让div在页面加载时弹出。我甚至不需要事件侦听器…

然而,两个答案都很好,并帮助我弄清楚如何使原始代码工作,所以谢谢。: D

infowindow声明之后创建一个函数来添加映射侦听器。该函数将创建一个闭包并冻结传递给它的i值。

...
infowindow = new google.maps.InfoWindow({
        content: contents
    });
var addListener = function (i) {
google.maps.event.addListener(positions[i], 'click', function(){
        infoWindows[i].open(map, positions[i]);                 
    });
   ...
}

然后在for循环中调用它:

addListener(i);

内部函数正在关闭变量 i。在for循环结束时,所有的i都将是points.length。这是一个非常常见的Javascript错误:

JavaScript闭包内部循环-简单的实际例子