如何解决如何清除反应中的传单地图以便我可以映射新数据?
我正在尝试在获取要映射的新数据时清除传单地图以进行反应,但我不确定如何处理此问题。我看到了这个 post,但不确定如何应用它。
现在我有一个函数可以获取我加载的 2 个 geojson 中的 1 个。
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 });
});
}
};
这只是为了降低功能的测试。现在,如果我在初始加载后单击 fetch data button
,传单会在顶部映射新的 geojson。我将如何清除映射信息以便新的 geojson 被映射到新的?
我这里有一个代码沙盒:
https://codesandbox.io/s/leaflet-test-forked-8hm3i?file=/src/Leaf.js:550-573
解决方法
在 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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。