0
我試圖在Google地圖中創建交互式標記。這裏是陣列來創建標記:匿名函數內循環內變量作用域
var markers = [
{"id":17,"ti":"33 Star Hotel","lat":3.14648,"lng":101.711,"ty":5,"lid":"3","desc":""},
{"id":9,"ti":"Aquaria KLCC","lat":3.15392,"lng":101.713,"ty":10,"lid":"3","desc":""},
{"id":28,"ti":"Batu Ferringhi","lat":5.47436,"lng":100.247,"ty":15,"lid":"4","desc":""},
];
的標記被添加到地圖Ñ如果所述標記的位置ID 蓋是等於n。
當點擊一個標記,我希望被顯示的標記數組索引,但它們都顯示出我(markers.length)的最終值。
function map_center(n) {
for (var i = 0; i < markers.length; i++) {
if (markers[i].lid == n) {
var m = new google.maps.Marker({
position: { lat: markers[i].lat, lng: markers[i].lng },
map: map,
title: markers[i].ti,
icon: icons[markers[i].ty],
});
m.addListener("click", function(){
alert("click:" + i);
});
markers[i].dom = m;
}
}
}
不知何故,匿名函數需要一個參數來獲得我當前值的副本。我在這裏發現了這個解決方案對SO和它的作品,但我不喜歡傳遞參數是這樣的:
var m = new google.maps.Marker({
position: { lat: markers[i].lat, lng: markers[i].lng },
map: map,
title: markers[i].ti,
icon: icons[markers[i].ty],
i: i
});
m.addListener("click", function(){
alert("click:" + this.i);
});
如何來正確地完成?
謝謝@FelixKling!我不知道loop_中的花哨詞__!這正是我期待的! –