简体   繁体   中英

Mapbox GL setData to update layer with multiple markers

I have a Mapbox GL map with a single layer and multiple markers on that layer, I am trying to update a specific marker, so I am using setData in order to update only one marker but setData will reset the whole layer markers to add only that I am trying to update as the single marker on the whole layer, thus removing all old markers.

By trying to add multiple markers in GEOJson format as an array of GEOJson objects as shown below I get an error:

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

code:

          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"
            }
          }]);

Will appreciate it so much if someone can please help by telling me what I am doing wrong / missing here, thanks

setData expects a complete GeoJSON object (not just it's features) or a url pointing to a GeoJSON object.

You'll need to manage the state of the GeoJSON in your code and update the entire object via setData when a change is made.

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/ is a good example that demonstrates this behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM