javascript - 清除先前的 GeoJSON 对象
问题描述
我正在开发一个应用程序,我试图清除以前的 Leaflet GeoJSON 层以支持当前层。我都尝试过map.removeLayer(geojsonPoint)
,map.clearLayer(geojsonPoint)
但它们似乎都不适用于我的功能。这是我尝试解决的方法:
function addPoints(geoJsonMain, responseJson) {
console.log(geoJsonMain);
let pointData = L.geoJSON(geoJsonMain);
for (let j = 0; j < responseJson.data.length; j++) {
for (let i = 0; i < geoJsonMain.features.length; i++) {
// console.log(geoJsonMain.features[i].properties.stateCode);
if (geoJsonMain.features[i].properties.stateCode !== responseJson.data[j].states) {
map.removeLayer(pointData)
// console.log(geoJsonMain.features[i].properties.stateCode, ' ', responseJson.data[j].states)
} else {
pointData.addTo(map);
map.fitBounds(pointData.getBounds());
}
}
}
}
但是当我在那里有 removeLayer(pointData) 时,它不会清除任何东西。为什么不清除当前的 L.geoJSON 层?有关完整布局,请参阅链接的 repl.it。它正在寻找州的缩写(即 NY、NC、SC 等)
解决方案
我可能错过了您要完成的工作,但这会占用您的新点,将它们添加到地图中并清除旧点。
function addPoints(geoJsonMain, responseJson) {
let pointData = L.geoJSON(geoJsonMain);
pointData.addTo(map);
map.fitBounds(pointData.getBounds());
if(oldPoints){
oldPoints.removeFrom(map);
}
oldPoints = pointData;
}
oldPoints 是一个全局变量,我将其设置为 false 作为标志,以避免在第一次运行时运行或抛出错误。第一次运行后,它将存储旧点并在每次后续运行时清除它们。
推荐阅读
- angular - 网络提供商出了问题?
- spring-boot - 数据表加载太慢
- autodesk-forge - 使用设计自动化 API 将 Revit 打印到 PDF - 不允许打印机设置、任何其他解决方法或解决方案
- android - JSONObject Azure 函数
- reactjs - 如何将 React 代码转换为 ClojureScript 代码?
- python - 不能声明双数组?
- javascript - 如何将请求 ID 值传递给模态?
- angular - Angular 7 Service 是未定义的异常
- excel - 修改通过 VBA IDE 创建的子和函数体的任何可能性
- swift - 结构作为具有完成功能的函数中的参数 - Swift