我試圖設置一個Google地圖實例,其中一些內容是動態生成的一組點。谷歌地圖事件監聽器在Javascript'for'循環中無法正常工作
現在,我使用for循環來循環任意數量的緯度和經度值,並創建標記是地圖上的那些點。
我試圖添加與這些標記中的每一個相對應的信息窗口,並讓它們在您單擊標記時彈出。
但是,我遇到了一些麻煩。它看起來像我的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.
}
}
其中「地圖」是google.maps.Map的實例,並彈出窗口的每個實例都將在不同完成品。
我調用這個函數在頁面加載時,它增加了位置和標記我的地圖:
drawMap([[13.283 , 162.232], [18.232 , 112.223], [17.233, 80.293]]);
有誰知道爲什麼我不能動態地創建事件監聽器?任何幫助將不勝感激!
在此先感謝。 :)
編輯:
原來,這裏的要求是隻具備div的彈出頁面加載時。我甚至不需要事件監聽器...
但是,這兩個答案都很好,並幫助我弄清楚如何使原代碼工作,所以謝謝。 :D
這真是個好主意!會從來沒有想過 - 謝謝:) – Ron