Raz Buchnik
Raz Buchnik

Reputation: 8411

How to remove specific feature in feature collection under geojson source in a places layer?

I got this:

map.addLayer({
  "id": "places",
  "type": "symbol",
  "source": {
    "type": "geojson",
    "data": {
      "type": "FeatureCollection",
      "features": features
    }
  },
  "layout": {
    "icon-image": "{icon}-15",
    "text-field": "{title}",
    "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"],
    "text-offset": [0, 0.6],
    "text-anchor": "top"
  }
});

Where features is array of objects like this:

{
  "id": SOME_ID,
  "type": "Feature",
  "properties": {
    "title": SOME_TITLE,
    "icon": "monument"
  },
  "geometry": {
    "type": "Point",
    "coordinates": SOME_COORDINATES
  }
}

I want to delete this specific feature, NOT THE WHOLE places LAYER, how can it be done?

I have tried to create for each feature, a designated layer with predefined ID, but when tried to remove it using map.removeLayer(SOME_ID) this told me that the layer id does not exist.

How to delete specific geojson feature from feature collection in mapbox, without delete the wole layer, just the json data?

Upvotes: 3

Views: 2568

Answers (1)

Stepan Kuzmin
Stepan Kuzmin

Reputation: 1031

If you want to hide the feature on the map, then you don't have to remove it from the source. You can filter this feature out using filter, so it wouldn't be rendered on the map.

Consider example:

    map.addLayer({
      id: 'points',
      type: 'circle',
      source: {
        type: 'geojson',
        data: {
          type: 'FeatureCollection',
          features: [
            {
              type: 'Feature',
              id: 1,
              properties: {},
              geometry: {
                type: 'Point',
                coordinates: [127.61718749999999, 66.51326044311185]
              }
            },
            {
              type: 'Feature',
              id: 2,
              properties: {},
              geometry: {
                type: 'Point',
                coordinates: [79.1015625, 72.50172235139388]
              }
            },
            {
              type: 'Feature',
              id: 3,
              properties: {},
              geometry: {
                type: 'Point',
                coordinates: [61.17187499999999, 31.952162238024975]
              }
            }
          ]
        }
      },
      filter: ['!=', '$id', 3]
    });

This will render all features except feature with id=3.

You can also set this kind of filters using map.setFilter method.

map.setFilter('my-layer', ['==', 'name', 'USA']);

Edit:

If you really want to remove a specific feature from the source, you can filter this feature from the features array and update the source using setData:

map.getSource('places').setData({
  "type": "FeatureCollection",
  features
});

Upvotes: 2

Related Questions