我想用存储在数据库中的位置的标记填充谷歌地图,然后允许用户通过双击要删除的标记来删除任何标记。使用下面的代码填充地图,但是当双击任何标记时,最后一个标记被删除。
我认为这种情况正在发生,因为每次都将双击事件侦听器重新分配给当前标记,但我不知道如何阻止这种情况发生。
我在这里设置了一个 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++;
}
}
任何帮助都会很棒
更新:
我通过将删除处理函数更改为
//add delete handler
google.maps.event.addListener(marker, 'dblclick', function(event) {
this.setMap(null);
delete markers.locations[this.id];
});
并在创建标记时向标记添加 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
});