如何清除react中的传单地图以便我可以映射新数据?

IT技术 javascript reactjs leaflet react-leaflet
2021-05-12 09:08:14

我正在尝试在获取要映射的新数据时清除传单地图以进行react,但我不确定如何处理此问题。我看到了这篇文章,但不确定如何应用它。

现在我有一个函数可以获取我加载的 2 个 geojsons 中的 1 个。

应用程序.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 });
        });
    } 
  };

这只是为了降低功能的测试。现在,如果我fetch data button在初始加载后单击,传单会在顶部映射新的 geojson。我将如何清除映射信息以便新的 geojson 被映射到新的?

我这里有一个代码沙箱:

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

1个回答

Choro组件外部创建一个变量

let savedGeojson = {};

在 useEffect 内部使它与L.choropleth实例相等如果存在,则从地图中删除 geojson,否则通过替换上次保存的来保存新的 geojson。

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;
}

演示