I am working with the leaflet api.Where i have added custom control for marker.
And i have a button which tends to remove all markers.
Problem
Through wrapping, i have to remove all markers but function not working....Browser not giving any console error, so i am in dark, didn't fully understand the structure of api.
Script
var markers = new L.FeatureGroup();
map.on('click', function markerPlace(e) {
//L.marker(e.latlng, { icon: markerIcon, draggable: true }).addTo(map);
marker = L.marker(e.latlng, { icon: markerIcon, draggable: true }).addTo(map);
markers.addLayer(marker);
map.off('click', markerPlace);
});
}).addTo(map);
//onClick this button we have to remove all marker
<button id="removeMarker">Remove Markers</button>
$('#removeMarker').click(function (e) {map.removeLayer(markers) });
If someone have idea about that please help or any kind of reference will be appreciated.Thanks for your time
When you properly ident your code you can easily spot the first mistake:
var markers = new L.FeatureGroup();
map.on('click', function markerPlace(e) {
//L.marker(e.latlng, { icon: markerIcon, draggable: true }).addTo(map);
marker = L.marker(e.latlng, { icon: markerIcon, draggable: true }).addTo(map);
markers.addLayer(marker);
map.off('click', markerPlace);
});
}).addTo(map); // <- What is this doing here
That should give you a big fat console error. I'm assuming that belongs to your L.FeatureGroup
like this:
var markers = new L.FeatureGroup().addTo(map); <- Moved to here
map.on('click', function markerPlace(e) {
//L.marker(e.latlng, { icon: markerIcon, draggable: true }).addTo(map);
marker = L.marker(e.latlng, { icon: markerIcon, draggable: true }).addTo(map);
markers.addLayer(marker);
map.off('click', markerPlace);
});
So you want the marker to be added to the L.FeatureGroup
called markers
then why add them to the map?
marker = L.marker(e.latlng, { icon: markerIcon, draggable: true }).addTo(map);
That should be changed to:
marker = L.marker(e.latlng, { icon: markerIcon, draggable: true }).addTo(markers);
So in short: on the map's click event you're trying to remove the markers featurelayer from the map, which hasn't properly been added and you've added the markers to the map, not the featuregroup.
PS: You want to remove the markers but what you are actually trying to do is removing the entire featuregroup. If you want to leave the featuregroup in place and only remove the markers you can just as well use the clearLayers
method of L.FeatureGroup
:
markers.clearLayers();