有一种干净的方法可以清除地图框要素集合而不丢失图层和源吗?

use*_*686 1 mapbox mapbox-gl-js

我通过添加链接到它们的源和图层来初始化 Mapbox 地图。

    mapbox.addSource(MY_SOURCE, {
        'type': 'geojson',
        'data': {
            'type': 'FeatureCollection',
            'features': [],
        },
    });

    mapbox.addLayer({
        'id': MY_LAYER,
        'type': 'circle',
        'source': MY_SOURCE,
        'paint': {
            'circle-radius': 6,
            'circle-color': '#d31467',
        },
    });
Run Code Online (Sandbox Code Playgroud)

我的目标是 - 我希望一次完成这些定义 - 如果我需要更新源代码,我只需:

    mapbox.getSource(MY_SOURCE).setData(geojson);
Run Code Online (Sandbox Code Playgroud)

有时我需要清除所有多边形、所有点、所有东西。我怎样才能做到这一点而不丢失所有这些定义?我只能看到.removeSource, .removeLayer- 这告诉我实际上需要重新创建这些定义。

有没有一种破坏性较小的方法呢?

Sca*_*ize 5

您在这里有两个选择:

  1. 隐藏图层

    map.setLayoutProperty(<layer-id>, 'visibility', 'none');
    
    Run Code Online (Sandbox Code Playgroud)
  2. 通过设置空的 geojson 从源中删除所有功能

    map.getSource(<source-id>).setData({
      type: 'FeatureCollection',
      features: []  // <--- no features
    });
    
    Run Code Online (Sandbox Code Playgroud)

此外,删除并重新添加源和图层可能不是最糟糕的选择,具体取决于您想要执行此操作的频率。