I'm using an L.easyButton to add and remove a leaflet marker based on the current location. This is my code:
var marker;
L.easyButton({
states: [{
stateName: 'on',
title: 'Add Marker',
onClick: function(btn, map) {
map.locate({ setView: true, maxZoom: 16 });
function onLocationFound(e) {
marker = L.marker(e.latlng).addTo(map);
}
map.on('locationfound', onLocationFound);
btn.state('off');
}
}, {
stateName: 'off',
title: 'Remove Marker',
onClick: function(btn, map) {
if (map.hasLayer(marker)) {
map.removeLayer(marker);
//map.removeControl(marker);
}
btn.state('on');
}
}]
}).addTo(map);
The code works well when added and removed the marker for the first time. But when I clicked the button again, the marker can added, but it failed to be removed.
FYI, the button state can be changed successfully, just the removal function is not working.
I have tried these both code lines in the remove function, but it didn't work.
map.removeLayer(marker);
map.removeControl(marker);
How should I improve the code? Thanks in advance.