【问题标题】:Clear previous GeoJSON Object清除先前的 GeoJSON 对象
【发布时间】:2020-02-20 18:50:27
【问题描述】:

我正在处理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 等)

【问题讨论】:

    标签: javascript leaflet gis


    【解决方案1】:

    我可能错过了您想要完成的任务,但这会获取您的新点,将它们添加到地图并清除旧点。

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

    【讨论】:

    • 这正是我想要的。非常感谢您,先生!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-27
    • 1970-01-01
    相关资源
    最近更新 更多