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 thegetArray()
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 thename
property which can be retrieved using the layerget()
method.Finally, iterate over the filtered layers and remove them from the map.
Alternatively, you can also use the layer collection's internal
forEach()
method for similar results.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.