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

这一生的挚爱 提交于 2021-01-07 04:09:55

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/65397400/how-do-i-clear-a-leaflet-map-in-react-so-i-can-map-fresh-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!