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
  • To understand what your problem is and then suggest the solution, more of your code would be helpful. Please edit your question and add relevant code. – TomazicM Aug 9 at 9:02
  • Ok, I'll do and edit the post – Suseday Aug 9 at 10:16

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.

| improve this answer | |
  • Wow, so easy and it works! Wonderfull! Yes, it is really the layer I want to remove because the function that calls it removes the last route that was pinned to the map. Thanks! – Suseday Aug 9 at 11:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.