我想用存儲在數據庫中的位置的標記填充Google地圖,然後允許用戶通過雙擊要刪除的標記來刪除任何標記。使用下面的代碼填充地圖,但是當雙擊任何標記時,最後一個標記被刪除。刪除存儲在對象中的谷歌地圖標記
我認爲這是因爲雙擊事件監聽器被重新分配到當前標記,但我不知道如何阻止這種情況發生。
我有一個的jsfiddle在這裏設立http://jsfiddle.net/simonbarker/TA4HP/
var markers = {"locations": [{"name" : "UK 1", "date" : "Nov 1", "lat" : 51, "lng" : 0.164},
{"name" : "France 1", "date" : "Nov 2", "lat" : 50, "lng" : 0.164},
{"name" : "France 2", "date" : "Nov 2", "lat" : 49, "lng" : 0.164}]
};
var map;
var center = new google.maps.LatLng(markers.locations[1].lat,markers.locations[1].lng);
var mapOptions = {
zoom: 8,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
createMarkers();
//create markers by traversing throught the markers object
function createMarkers(){
var i = 0;
while(markers.locations[i]){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(markers.locations[i].lat, markers.locations[i].lng),
animation: google.maps.Animation.DROP,
map: map
});
//store marker in the locations object
markers.locations[i].marker = marker;
//add delete handler
google.maps.event.addListener(marker, 'dblclick', function(event) {
marker.setMap(null);
delete markers.locations[i];
});
i++;
}
}
任何幫助將是巨大的
UPDATE:
我解決了這個改變刪除處理函數
//add delete handler
google.maps.event.addListener(marker, 'dblclick', function(event) {
this.setMap(null);
delete markers.locations[this.id];
});
,創造它時,
var marker = new google.maps.Marker({
id: i,
position: new google.maps.LatLng(markers.locations[i].lat, markers.locations[i].lng),
animation: google.maps.Animation.DROP,
map: map
});
好的,這是有道理的 - 它有點像一個解引用問題(我甚至試圖通過在變量名前加一個&來解決它),這就解釋了原因。感謝您的鏈接,我找到了另一種方式,但你的整潔,我認爲 – SimonBarker
請注意,你接受的答案是API V2,並不適用於API V3。 – Marcelo
而這將是因爲在我急躁時我接受了錯誤的答案:-) – SimonBarker