Hiro Protagonist
Hiro Protagonist

Reputation: 483

Change any polygon's colour in a single layer

I am using mapbox gl js to render coloured (i.e. filled) polygons, whose sources are geojson feature collections. I would like to change the polygon colours on the fly on the client, based on user actions. The following constraints apply/things have been tried:

  1. I'm using Mapbox GL JS - not Leaflet, etc.
  2. I would like to add all polygons to a single layer (i.e. feature collection per mapbox layer) as adding a new layer for each polygon appears to have a disastrous effect on performance (I have several thousand polygons with several thousand coordinates each), and the
  3. It ought to be possible to identify individual polygons by their ID; this is where I struggled as well: I am not sure how to identify all the polygons after they have been added to the layer in the form of a feature collection. Failing that - how can they be identified, if not by ID ?

Please supply a working example that shows at least two polygons being added to a single layer, and their colour being changed after they have been added (random colour is fine, I'm interested in the principle)

Unfortunately, the SO questions here, here, and here aren't quite what I need. This question comes very close, but doesn't show how to actually apply the change. It simply mentions setStyle() :-(

Thanks for your help !

Upvotes: 2

Views: 1572

Answers (2)

Steve Bennett
Steve Bennett

Reputation: 126215

It sounds like you want to make a "choropleth" - polygons color coded by some data property.

I am not sure how to identify all the polygons after they have been added to the layer in the form of a feature collection.

Make sure each polygon has an id property. In GeoJSON this would be like:

"properties": {
    "id": 451,
    "myvalue": 0.8
}

You basically have two ways you can do coloring:

  1. Store the data separately, and generate a big data-driven property that maps the id onto its required color.
  2. Store the data on the feature, and use a small data-driven property that converts the data into a color.

Rather than request a worked example, I suggest you use the API docs to get as close as you can, and ask a specific question when you get stuck.

Upvotes: 2

AndrewHarvey
AndrewHarvey

Reputation: 3055

You want to use data driven styling which lets you use a single Layer but different styles based on the properties of each Feature within that Layer. See an example at https://www.mapbox.com/mapbox-gl-js/example/data-driven-circle-colors/

Upvotes: 1

Related Questions