How to remove layers by name - openlayers 3
Asked Answered
M

2

5

I was add vector layer with wkt source to map with below code:

var SelectVector = null;

for (var i = 0; i < wktarray.length; i++) {
    var wkt = wktarray[i];
    var format = new ol.format.WKT();
    var feature = format.readFeature(wkt, {
        dataProjection: 'EPSG:4326',
        featureProjection: 'EPSG:4326'
    });
    SelectVector = new ol.layer.Vector({
        source: new ol.source.Vector({
            features: [feature]
        }),
        style: new ol.style.Style({
            fill: new ol.style.Fill({
                color: 'rgba(255, 255, 255, 0.2)'
            }),
            stroke: new ol.style.Stroke({
                color: '#ffcc33',
                width: 2
            }),
            image: new ol.style.Circle({
                radius: 7,
                fill: new ol.style.Fill({
                    color: '#ffcc33'
                })
            })
        })
    });
    map.addLayer(SelectVector);
    SelectVector.set('name', 'selectvector');
}

Now, I want remove this vector layer from map. wrote below code but, it does not remove all layer with selectvector name.

map.getLayers().forEach(function (layer) {
    if (layer.get('name') != undefined & layer.get('name') === 'selectvector') {
        map.removeLayer(layer);
    }
});

what is wrong?

Majuscule answered 17/10, 2017 at 8:11 Comment(0)
L
14

I think the problem is that removeLayer changes the same collection that you are cycling.

Try somthing like this

var layersToRemove = [];
map.getLayers().forEach(function (layer) {
    if (layer.get('name') != undefined && layer.get('name') === 'selectvector') {
        layersToRemove.push(layer);
    }
});

var len = layersToRemove.length;
for(var i = 0; i < len; i++) {
    map.removeLayer(layersToRemove[i]);
}

Also note that you are missing an "&" in your if condition.

Lanthanide answered 17/10, 2017 at 12:31 Comment(0)
T
3

Like fradal83 pointed out, you are changing the collection while cycling.

Instead of cycling from the first, you could inverse it (start with the last one up to the first). That way, removing an item would not affect the loop.

Tearle answered 18/10, 2017 at 12:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.