Reputation: 61
I am using leaflet to display maps on my site. I want user to show and save his address on the map (by placing a marker) so in my code, if user double clicks, a marker will be placed on the map. The problem is I don't want to disable double click zoom. So when user double clicks again, the previous marker should be deleted and a new marker should be added. I searched Stack Overflow and reached to this code
map.on('dblclick', addMarker);
var Marker;
function addMarker(e) {
//remove previous markers
map.removeLayer(Marker);
// Add marker to map at click location; add popup window
Marker = new L.marker(e.latlng,{draggable:true}).addTo(map);
}
But after adding "map.removeLayer (Marker);" not only double click zoom stopped working, but also no marker is added to map anymore Summary: I always want to keep the last marker added to map
Upvotes: 2
Views: 1149
Reputation: 53225
The script stops working on first double click because it tries to remove Marker
which is not assigned yet at initialization.
Once the error occurs, the rest of your JS function stops: no marker added, no double click zoom.
Simply check that Marker
is assigned before trying to remove it.
map.on('dblclick', addMarker);
var Marker;
function addMarker(e) {
//remove previous markers
if (Marker) {
map.removeLayer(Marker);
}
// Add marker to map at click location; add popup window
Marker = new L.marker(e.latlng, {
draggable: true
}).addTo(map);
}
Demo: http://jsfiddle.net/3v7hd2vx/26/
Upvotes: 4