Skip to content
Advertisement

How do I clear a leaflet map in react so I can map fresh data?

I am attempting to clear a leaflet map in react when fetching new data to map, and i am unsure how to approach this. I saw this post but not sure how exactly to apply it.

Right now I have a function that fetches 1 of 2 geojsons I have loaded.

App.js

JavaScript

This is merely a test to get the functionality down. Right now if I click the fetch data button after the initial load, leaflet maps the new geojson on top. How would I clear the mapped information so that the new geojson is mapped fresh?

I have a code sand box here:

https://codesandbox.io/s/leaflet-test-forked-8hm3i?file=/src/Leaf.js:550-573

Advertisement

Answer

Create a variable outside Choro component.

JavaScript

Inside useEffect make it equal with the L.choropleth instance. If it exists remove the geojson from the map else save the new one by replacing the last saved.

JavaScript

Demo

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement