3
votes

I'm trying to create a choropleth map using mapbox-gl. In the example choropleth maps, it looks like they set the feature's paint fill colour based on the properties of the feature. Is there a way to set the colour by accessing a map?

ie. I have tiles each with a unique id in the feature property called id. I also have a json which maps each id with a value and would like to access those values to set the colour.

Is this possible? or am i limited to only being able to access values in the feature properties?

2

2 Answers

4
votes

I'm not entirely sure if I understood your question correctly. But I think what you are trying to achieve can be done with expressions:

const geojson = {
  type: 'FeatureCollection',
  features: [
    {
      type: 'Feature',
      properties: {
        id: 'foo'
      },
      geometry: {
        /* */
      }
    }
  ]
};

const values = {
  foo: 'green',
  bar: 'red',
  baz: 'blue'
};

map.addLayer({
  // ...
  paint: {
    'fill-color': [
      [
        'get',
        // get the id property and use it as a key into "values"
        ['get', 'id'],
        values
      ]
    ]
  }
});

See the get expression: https://www.mapbox.com/mapbox-gl-js/style-spec#expressions-get

2
votes

Update from 04.2018: Since some moment constructions like

 [
    'get',
    // get the id property and use it as a key into "values"
    ['get', 'id'],
    values
  ]

stopped to work. The following exception occures: 'Bare objects invalid. Use ["literal", {...}]'. Now it is necessary to use type expressions, like this:

[
 'get',
 ['string', ['get', 'id'],
 ['literal', values]
]

See this and this for reference.