zipzip12
zipzip12

Reputation: 41

How to style an individual point with Mapbox?

I am building a web app based on Mapbox and want to show more information about a subset of points in a table, then be able to select a row in the table (corresponding to a point on the map) and highlight the point on the map by virtue of selecting the row in the table. I selecting the current points on view through a Node.js server, then populating a DataTables table with those points. Ideally, I could then click the row in the DataTable and have the corresponding point styled accordingly. Is there a way to do this? Thank you!

Upvotes: 0

Views: 1424

Answers (1)

Steve Bennett
Steve Bennett

Reputation: 126105

You haven't given much information about how your map is set up, but I'm going to assume you have a data source (either GeoJSON or vector tiles) and a layer that is currently displaying all your points. (I'm not sure what ou mean by a "DataTables table").

There are two methods

With a highlight layer

Let's say there is an attribute on every row called placeNumber.

1: Create a highlight layer:

map.addLayer({ 
  id: 'place-highlight',
  type: 'circle', 
  source: mysource,
  paint: {
    'fill-color': 'yellow',
    'circle-radius': '20',
    'fill-opacity': 0.5
  },
  filter: ['==', 'placeNumber', -1]
});

2: Update the filter:

map.setFilter('place-highlight', ['==', 'placeNumber', selectedPlaceNumber]);

With SetFeatureState

To make this work, you need to be able to access the FeatureID of the selected feature.

When the row is clicked:

map.setFeatureState({ source: 'place', id: previousSelectedFeatureId }, { selected: false })
map.setFeatureState({ source: 'place', id: selectedFeatureId }, { selected: true })
previousSelectedFeatureId = selectedFeatureid;

And use the feature state within your paint properties:

paint: {
   'circle-color': ['case',
      ['==', ['feature-state', 'selected'], true], 'yellow',
      'black'
      ]
}

That is, "circle color is yellow for points that have a "selected" feature-state of true, and black otherwise".

Upvotes: 1

Related Questions