[GIS] OpenLayers: How to remove a layer based on a value

javascriptopenlayersreact

In React, I'm using a pagination that returns a certain amount of results on each page. Using the address of these results, I convert them to longitude and latitude using a geo-coder package and set my markers.

setMarkers(map){
    const geoCode = new GeoCode();
    const dataLength = this.props.getData.length;
    for(var i = 0; i < dataLength; i++) {
        geoCode.geolookup(this.props.getData[i].address)
        .then(result => {
            // ADD A LAYER EACH TIME AN ADDRESS IS CONVERTED TO
            // LONGITUDE AND LATITUDE
            map.addLayer(new VectorLayer({
                source: new VectorSource({
                    features: [new Feature({
                        geometry: new Point(fromLonLat([result[0].lng, result[0].lat])),
                        name: 'Marker',
                        id: 'this.props.getData[i].id_number'
                    })],
                }),
                name: 'Marker', // THE NAME OF THE VECTOR LAYER
                zIndex: 5
            }))
        })
    }
    this.mapClickHandler(map)
}

However, each time the user goes to a new page, all the marker layers should be removed so that I can add new marker layers based on the new results.
I know that I have to remove layers like this:
map.removeLayers()

But how do I use this to remove layers based on the layer name value 'Marker'

Best Answer

One option is to get the collection of the map layers using the getLayers() method. Then get a reference to the underlying array of layers using the getArray() method.

Now that you have an array of the map layers, utilize the native array filter() method in order to filter the array of layers based on the name property which can be retrieved using the layer get() method.

Finally, iterate over the filtered layers and remove them from the map.

map.getLayers().getArray()
  .filter(layer => layer.get('name') === 'Marker')
  .forEach(layer => map.removeLayer(layer));

Alternatively, you can also use the layer collection's internal forEach() method for similar results.

map.getLayers().forEach(layer => {
  if (layer && layer.get('name') === 'Marker') {
    map.removeLayer(layer);
  }
});

However, this approach has a slight caveat since you are removing layers as you are iterating over them (which may result in layers being skipped in some cases). With that being said, it's better to go with the first approach where the reference layers are filtered and then subsequently removed.

Related Question