首页 > 解决方案 > 清除先前的 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 等)

标签: javascriptleafletgis

解决方案


我可能错过了您要完成的工作,但这会占用您的新点,将它们添加到地图中并清除旧点。

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 作为标志,以避免在第一次运行时运行或抛出错误。第一次运行后,它将存储旧点并在每次后续运行时清除它们。


推荐阅读