8

我有一个 Mapbox GL 地图,其中有一个图层和该图层上的多个标记,我正在尝试更新特定标记,因此我使用 setData 仅更新一个标记,但 setData 将重置整个图层标记以仅添加该标记我正在尝试更新为整个图层上的单个标记,从而删除所有旧标记。

通过尝试以 GEOJson 格式添加多个标记作为 GEOJson 对象数组,如下所示,我收到错误:

Uncaught Error: Input data is not a valid GeoJSON object.

代码:

          map.getSource('cafespots').setData([{
            "type": "Feature",
            "geometry": {
              "type": "Point",
              "coordinates": [31.331849098205566, 30.095422632059062]
            },
            "properties": {
              "marker-symbol": "cafe"
            }
          },{
            "type": "Feature",
            "geometry": {
              "type": "Point",
              "coordinates": [31.39, 30.10]
            },
            "properties": {
              "marker-symbol": "cafe"
            }
          }]);

如果有人可以通过告诉我我做错了什么/在这里丢失来帮助我,将非常感激,谢谢

4

1 回答 1

20

setData需要一个完整的 GeoJSON 对象(不仅仅是它的功能)或一个指向 GeoJSON 对象的 url。

您需要在代码中管理 GeoJSON 的状态,并setData在发生更改时更新整个对象。

var geojson = {
  "type": "FeatureCollection",
  "features": []
};

map.on('load', function() {
  map.addSource('custom', {
    "type": "geojson",
    "data": geojson
  });

  // Add a marker feature to your geojson object
  var marker {
    type: 'Feature',
    geometry: {
      type: 'Point',
      coordinates: [0, 0]
    }
  };

  geojson.features.push(marker);
  map.getSource('custom').setData(geojson);
});

https://www.mapbox.com/mapbox-gl-js/example/measure/是展示这种行为的一个很好的例子。

于 2016-03-28T04:05:26.723 回答