簡體   English   中英

Google Maps事件偵聽器在Javascript'for'循環中無法正常工作

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

我正在嘗試設置一個Google地圖實例,其中為一組點動態生成一些內容。

現在,我正在使用for循環遍歷任意數量的緯度和經度值,並創建標記是地圖上的那些點。

我正在嘗試添加與這些標記相對應的信息窗口,並在單擊標記時彈出它們。

但是,我遇到了一些麻煩。 除了eventListener部分之外,它看起來像我的for循環基本上創建了一切正常工作:

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的一個實例,popUps的每個實例在最終產品中都會有所不同。

我在頁面加載時調用此函數,這會向我的地圖添加位置和標記:

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閉包 - 簡單實用的例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM