从 Leaflet 地图中删除 geoJSON

Remove geoJSON from Leaflet map

我有一个函数可以检索带有地震数据的 JSON,我将其添加到 Leaflet 地图中,它会在 10 秒后再次检索 JSON(用于刷新数据):

function fetchQuake() {
        fetch('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson')
        .then(function(res) {
            if (res.ok === true) {
                return res.json();
            } else {
                alert('Geojson request failed.');
            }
        })
        .then(function(quake) {
                L.geoJSON(quake, {
                    style: function(feature) {
                        return feature.properties && feature.properties.style;
                    },
                    onEachFeature: onEachFeature,
                    pointToLayer: function(feature, latlng) {
                        return L.circleMarker(latlng, {
                            radius: 8,
                            fillColor: "#ff7800",
                            color: "#000",
                            weight: 1,
                            opacity: 1,
                            fillOpacity: 0.8
                        });
                    }
                }).addTo(map);

            myQuakeTimeout = setTimeout(function() {
                fetchQuake();
            }, 10000);
        });
}

以及从这些点清除地图的函数:

function clearQuake() {
    clearTimeout(myQuakeTimeout);
    L.geoJSON().clearLayers();
}

使用这些代码,超时停止了,但是地震点并没有离开地图,这是什么问题?

使用此代码,您的 clearQuake() 函数永远不会被调用,因此 L.geoJSON().clearLayers() 永远不会被执行。

这就是您的点不会离开地图的原因。

如果你想在添加新的提取点之前删除之前的点,你可以这样做:

/* ... */
.then(function(quake) {

    L.geoJSON().clearLayers();

    L.geoJSON(quake, {
        /* ... */
    }).addTo(map);

    myQuakeTimeout = setTimeout(fetchQuake, 10000);
});