javascript - 从 Leaflet map 中删除 geoJSON

标签 javascript json leaflet layer

我有一个函数,可以检索包含地震数据的 JSON,并将其添加到 Leaflet map 中,并在 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);
        });
}

还有一个从这些点清除 map 的函数:

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

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

最佳答案

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

这就是您的积分不会从 map 上消失的原因。

如果您想在添加新获取的点之前删除以前的点,您可以执行以下操作:

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

    L.geoJSON().clearLayers();

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

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

关于javascript - 从 Leaflet map 中删除 geoJSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45283462/

相关文章:

javascript - 添加 Angular-leaflet-directive 后 Grunt 构建失败

javascript - 获取 API 数据、呈现数据以及一般使用它的更好方法是什么

javascript - 在 mouseout 上关闭下拉菜单

javascript - 以编程方式访问 Raphael 路径

Javascript:仅在函数中使用特定参数

javascript - 如何在 JavaScript 文件中保存 JSON 字符串?

python - 索引 JSON 搜索 python

R Shiny - 使用文件输入将标记添加到传单 map

javascript - 如何删除以下热图中的现有标记并添加新的标记集?

javascript - Backbone js,绑定(bind)模型到 View