2012-11-20 56 views
0

我遇到了我的谷歌地圖網絡應用程序的問題,我試圖向地圖添加標記,然後當用戶點擊該標記時,標記的名稱出現。谷歌地圖標記事件顯示錯誤信息

我在陣列中存儲關於每個標記的信息,如下所示:

var citymap = {}; 
     citymap['edinburgh'] = { 
     center: new google.maps.LatLng(55.934120, -3.226569), 
     population: 284, 
     image:clueImage, 
     color: '#ff0000', 
     elementId:'clue1' 
     }; 
     citymap['clue2'] = { 
     center: new google.maps.LatLng(55.970783, -3.164594), 
     population: 284, 
     image:clueImage, 
     color: '#ff0000', 
     elementId:'clue2' 
     } 
     citymap['clue4'] = { 
     center: new google.maps.LatLng(55.939583, -3.202092), 
     population: 284, 
     image:clueImage, 
     color: '#ff0000', 
     elementId:'clue3' 
     } 
     citymap['clue9'] = { 
     center: new google.maps.LatLng(0, 0), 
     population: 284, 
     image:clueImage, 
     color: '#ff0000', 
     elementId:'clue1' 
     } 

我然後通過陣列環和標記添加到地圖:

for (var city in citymap) { 

     var playerMarker = new google.maps.Marker({ 
     position: citymap[city].center, 
     map: map, 
     icon: citymap[city].image 
     }); 

     google.maps.event.addListener(playerMarker, "click", function() { 
     var elementConnected = citymap[city].elementId; 
    console.log(elementConnected); 
    }); 

     } 

一切如預期運作,然而當我點擊任何標記時,它們都會記錄數組中最後一個標記的值。我知道這是因爲那些循環結束的地方,但我想不出一種做法。

幫助將是非常有益的!

回答

0

我認爲這是Javascript中的普遍「封閉」問題,人們有。有人可能會給出這樣做的更好的方式,但我認爲你需要的是這樣的:

google.maps.event.addListener(playerMarker, "click", (function() { 
    return function() { 
     var elementConnected = citymap[city].elementId; 
     console.log(elementConnected); 
    }; 
})(city)); 

或者,如果可能的話,這取決於你的click事件中做的還有什麼,也許這:

google.maps.event.addListener(playerMarker, "click", (function(elementId) { 
    return function() { 
     var elementConnected = elementId; 
     console.log(elementConnected); 
    }; 
})(citymap[city].elementId)); 
+0

感謝您的幫助:D – nmyster