Change style of single feature in mapbox gl
Asked Answered
R

1

6

The examples for highlighting polygons in mapbox gl use a second layer and a filter function. Is it not possible to change the color of a single feature/polygon in mapbox gl js, drawn from geojson source?

See https://www.mapbox.com/mapbox-gl-js/example/hover-styles/

Rocca answered 16/2, 2017 at 19:3 Comment(0)
G
1

It's possible to style a single feature using a data driven style that responds uniquely to an attribute of a single feature. For instance, if you have a point dataset with an id attribute and you want id 450 to be yellow instead of blue.

{
  "id": "mypoints",
  "type": "circle",
  "paint": {
    "fill-color": {
      "property": "id",
      "type": "category",
      "stops": [[450, "yellow"]],
      "default": "blue"
    }
  }
}

Caveat 1: the "default" feature is not publicly available yet.

Caveat 2: This only works for style properties that support data-driven functions.

Gerthagerti answered 24/2, 2017 at 1:43 Comment(6)
The key part of my question is CHANGE the polygon style, not set the polygon style. I want to be able to change an individual feature/polygon on the fly, not when the style is initially created. Can I do that with this method?Rocca
Yes, that's what data-driven styling is. You can leave the data the same, and update the style to highlight a different bit of it.Gerthagerti
yes, but how do you call that...layer.setStyle()? because there is nothing in the docs that shows how to update the style of a layer that I can find other than adding a new layer...I must be missing something here as this seems like a basic featureRocca
That changes/reloads the entire map, right? I am thinking more traditional GIS with a basemap as my map style, then layers on top. It looks like this works with map.setPaintProperty() with using stops function.Rocca
Not sure I understand you. setStyle changes one layer. setPaintProperty changes one property of one layer (as does setLayoutProperty). Both are potentially extremely quick - there's no "reloads the entire map".Gerthagerti
Currently, the feature highlighting on click feels faster in my leaflet vector grid parcel viewer app compared to the mapbox gl js version, using the same vector tiles. I was trying to find a faster way to highlight an individual feature in mapbox gl js, but this does not seem possible. I'll provide examples soon.Rocca

© 2022 - 2024 — McMap. All rights reserved.