React Leaflet: Remove all current Leaflet-Search controls on Map

Viewed 19

I'm currently trying to display a search bar in a leaflet map using the leaflet-search plugin. However, I am dynamically displaying markers based on an API which means that my function that adds the search control is being called multiple times. Thus, the search control is being displayed like 4 times on page load.

To counteract this, I decided that it would be best to use the map.removeControl() or map.removeLayer() methods to check if there was a search bar present before adding another one. If there is one present, I want to remove all current search controls before adding another one.

My idea was to do something like this:

export default function UserSearch(props) {
    const map = useMap();
    let markerGroup = ...
    ...
    let searchControl = new L.Control.Search({
        layer: markerGroup,
        position:'topright',        
        initial: false,
        zoom: 12,
        marker: false,
    })
    map.eachLayer((layer) => {
        if (layer instanceof L.Control.Search) {
            map.removeControl(layer)
        }
    })
    map.addControl( searchControl );
}

However, this doesn't work as I can't seem to find when the layers are instanceof L.Control.Search nor am I sure if map.eachLayer() is even the function that contains the search controls.

I'm not sure how to approach this or how to circumvent this issue.

0 Answers
Related