[英]Broken JS Loop with Google Maps
我的代碼在下面,我遇到了幾乎相同的代碼的問題,並在此處將其修復在StackOverflow上,但是同樣,它無法正常工作。 我沒有更改工作代碼,但是我確實將其包裝在for...in
循環中,您將在下面看到。 問題是,無論我單擊哪個標記,它始終會觸發最后放置的標記/ infoWindow。
$(function(){
var latlng = new google.maps.LatLng(45.522015,-122.683811);
var settings = {
zoom: 10,
center: latlng,
disableDefaultUI:true,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("map_canvas"), settings);
$.getJSON('api',function(json){
for (var property in json) {
if (json.hasOwnProperty(property)) {
var json_data = json[property];
var the_marker = new google.maps.Marker({
title:json_data.item.headline,
map:map,
clickable:true,
position:new google.maps.LatLng(
parseFloat(json_data.item.geoarray[0].latitude),
parseFloat(json_data.item.geoarray[0].longitude)
)
});
var infowindow = new google.maps.InfoWindow({
content: '<div><h1>'+json_data.item.headline+'</h1><p>'+json_data.item.full_content+'</p></div>'
});
new google.maps.event.addListener(the_marker, 'click', function() {
infowindow.open(map,the_marker);
});
}
}
});
});
感謝您解決這個問題的人!
這是在創建每個事件處理程序閉包(函數)時的情況:
new google.maps.event.addListener(the_marker, 'click', function() {
infowindow.open(map,the_marker);
});
...每個變量都獲得對變量the_marker
的持久引用, 而不是創建閉包時的值。 因此,該閉包函數的所有副本都使用相同的值(循環中分配給它的最后一個值)。 關閉並不復雜( 更多信息請參見此處 ),但是我們只能說您不是第一個犯此錯誤的人。 :-)這很容易做到。
因此,您想要做的就是在循環迭代中捕獲the_marker
的值 ,這很容易做到:
new google.maps.event.addListener(
the_marker,
'click',
buildHandler(map, the_marker));
function buildHandler(map, marker) {
return function() {
infowindow.open(map, marker);
};
}
那里,我們有一個函數,該函數使用傳遞給函數的參數構建處理程序,並在每次循環迭代時調用該函數為我們創建處理程序。
對SO另一個問題的這個答案可能有助於您直觀地了解閉包如何訪問變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.