MapBox GeoJSON 清除所有标记?

MapBox GeoJSON clear all markers?

我想用 "new" 标记更新我的地图。所以首先重置所有可见标记。我将通过 Ajax 使用 geoJSON 阅读我的标记:

   $.ajax({
        url: 'dashboard/geoJSON',
        dataType: 'json',
        async: false,
        type: 'GET',
        success: function(geojson) {
            var locations = L.mapbox.featureLayer().addTo(map);
            locations.setGeoJSON(geojson); 
            // reset?

         }
    });

我会尝试:

L.mapbox.featureLayer().clearLayers();

在添加所有新标记之前重置,但它不起作用。有什么想法吗?

您应该清除 map 对象中的层,而不是 featureLayers,其中 layer 变量是包含所有标记的层:

map.removeLayer(layer);

将全局 L 对象视为某种 'generator'。您可以将其链接起来以创建地图、图层、标记等。您将通过链接地图将它们附加到特定地图。

我找到了解决方案:

success: function(geojson) {

            markers.forEach(function(entry) {
                map.removeLayer(entry);
            });

            locations = L.mapbox.featureLayer().addTo(map);
            locations.on('layeradd', function (e) {
                var marker = e.layer;
                markers.push(marker);
            });

            locations.setGeoJSON(geojson);

所以我使用'layeradd'方法手动推送我的数组,然后在设置新数组之前将其全部删除。