清除以前的 GeoJSON 对象

Clear previous GeoJSON Object

我正在研究 app,我试图清除以前的 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 作为标志,以避免 运行ning 或在第一次运行时抛出错误。在第一个 运行 之后,它将存储旧点并在随后的每个 运行.

中清除它们