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

//SWAP FILES AS EXAMPLE
  fetchData = () => {
    //MAP SHOULD CLEAR EVERYTIME NEW DATA IS FETCHED
    if(this.state.loaded === 1) {
      fetch(
        "https://raw.githack.com/datafaust/raw/main/cruise-prototype/hh_2020112300_2020120623_Saturday_02.geojson"
      )
        .then((response) => response.json())
        .then((geojson) => {
          this.setState({ geojson, loaded: 2 });
        });

    } else {
      fetch(
        "https://raw.githack.com/datafaust/raw/main/cruise-prototype/hh_2020112300_2020120623_Saturday_03.geojson"
      )
        .then((response) => response.json())
        .then((geojson) => {
          this.setState({ geojson, loaded: 1 });
        });
    } 
  };

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.

let savedGeojson = {};

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.

useEffect(() => {
    if (Object.keys(props.geojson).length > 0) {
      if (savedGeojson) map.removeLayer(savedGeojson);
      savedGeojson = L.choropleth(props.geojson, {
        valueProperty: "DIFF", // which property in the features to use
        scale: ["white", "red"], // chroma.js scale - include as many as you like
        steps: 5, // number of breaks or steps in range
        mode: "q", // q for quantile, e for equidistant, k for k-means
        //style,
        onEachFeature: function (feature, layer) {
          layer.bindPopup(
            "Total " + feature.properties.DIFF + "<br>" //+
            // feature.properties.incidents.toLocaleString() +
            // " incidents"
          );
        }
      }).addTo(map);
    }
  }, [props.geojson]);

  return null;
}

Demo

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