Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove layers by name - openlayers 3

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?

like image 507
Farzaneh Talebi Avatar asked Oct 17 '17 08:10

Farzaneh Talebi


2 Answers

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.

like image 186
fradal83 Avatar answered Nov 20 '22 15:11

fradal83


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.

like image 3
Alexandre Dubé Avatar answered Nov 20 '22 15:11

Alexandre Dubé