TransWikia.com

Remove the last item from feature group in Leaflet

Geographic Information Systems Asked by Suseday on June 24, 2021

I just need to delete the last item in a featuregroup.

This code gives me that I have TWO objects in in the featureGroup featRouteL:

console.log("so many objects: "+featRouteL.getLayers().length);

Now, I just want to delete the LAST item. But how do I do that? I have tried so far but get error no matter what direction I go. I think I should get the id of the last layer item and then delete this layer id. Unfortunatly I get errors no matter what I do…

            var xlayers = featRouteL.getLayers();
            var xlength = xlayers.length;
            console.log("no of layers: "+xlength); //this gives me the correct no
            
            xlayers.forEach(function(layer) {
                //xlayers.removeLayer(layer); // -> xlayers.removeLayer is not a function
                //console.log(layer.get("name")); // -> layer.get is not a function
                //console.log(layer.getLayerId()); // -> Cannot read property '_leaflet_id' of undefined
            });             
            
            console.log("layers: "+xlength);
            
            //for (var i = 0; i < xlength; i++) {
                //l = xlayers.item(i); //-> xlayers.item is not a function
            //} 

One Answer

If just want to remove the last layer in the array of layers you get with featRouteL.getLayers() call, that's easy:

var layers = featRouteL.getLayers();
layers[layers.length - 1].remove();

Question here is if this is really the layer you want to remove.

Correct answer by TomazicM on June 24, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP