I have a featuregroup that adds circlemarkers and paths -- they are added in sequence and I need a way to create a function that will remove the last (2) in the _layers every time it's clicked.
I tried slicing but that doesn't work because it's not really an array.
Any thoughts on how to proceed? I've been searching stackoverflow for awhile and cannot find anything that matches what I'm trying to do.
Let's simply refer to Leaflet documentation:
You can use the methods the layerGroup/featureGroup provides to remove the last two layers from the group.
getLayers method returns an array of all the layers added to the group.eachLayer method iterates over the layers of the group, optionally specifying context of the iterator function.removeLayer method removes the layer with the given internal ID from the group.Leaflet's featureGroup is an extension of the layerGroup so all of these will work on featureGroup as well.
So, say that you have your layers set up like so:
// Layers:
var layers = L.layerGroup().addTo(map);
var marker = L.marker([51.5, -0.09]).addTo(layers);
var circle = L.circle([51.508, -0.11], {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.5,
radius: 500,
}).addTo(layers);
var polygon = L.polygon([
[51.509, -0.08],
[51.503, -0.06],
[51.51, -0.047],
]).addTo(layers);
You can use those layerGroup methods to remove the last two elements of the array:
// Pass the layerGroup to the function
function removeLastTwo(layerGroup) {
// Use getLayers to get the array
var layerArr = layerGroup.getLayers();
var minusOne = layerArr.length - 1;
var minusTwo = layerArr.length - 2;
// Use eachLayer to iterate the layerGroup
layerGroup.eachLayer((layer) => {
// Grab the index of the layer
var layerIndex = layerArr.indexOf(layer);
// Remove the last two elements of the layerGroup array
if (layerIndex === minusOne || layerIndex === minusTwo) {
layerGroup.removeLayer(layer);
}
});
}
Here is a live example, with this function attached to the click event listener of a button.