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?
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With