Mapbox GL setData to update layer with multiple markers

MKM picture MKM · Mar 27, 2016 · Viewed 9.7k times · Source

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

Answer

tristen picture tristen · Mar 28, 2016

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.