Reputation: 1424
I want to populate a Google Map with markers from locations stored in a database and then allow the user to delete any of the markers by double clicking the marker to be removed. Using the code below populates the map but when any of the markers are double clicked the last marker is removed.
I assume this is happening because the double click event listener is being reassigned each time to the current marker but I can't work out how to stop this happening.
I have a jsFiddle set up here 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++;
}
}
Any help would be great
UPDATE:
I solved this by changing the delete handler function to
//add delete handler
google.maps.event.addListener(marker, 'dblclick', function(event) {
this.setMap(null);
delete markers.locations[this.id];
});
and adding an id to the marker when creating it
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
});
Upvotes: 0
Views: 1984