1

Currently in the process of creating an interactive choropleth map with different coloured regions to indicate rainfall levels. The problem I have is that to do this in mapbox GL JS, you have to create different layers to indicate the different colour fills.

Is it possible to use nested functions? For example, filtering in the fill-color option to allow me to keep it as one logical layer.

Something like this:

map.addLayer({
    "id": "state-fills",
    "type": "fill",
    "source": "states",
    "interactive": true,
    "layout": {},
    "paint": {
        "fill-color": 'filter': [["==", "state", "stateproperty", 'color'],
                                ["==", "state", "stateproperty", 'nextColor']],
        "fill-opacity": 0.5
    }
});
1

You're right the GL JS API is limited at this time with regard to styling a single layer. As far as I know you can't use nested function like that. I understand that a feature called 'data-driven-styling' is a work in progress. You can see some discussion here

Until then I've seen examples such as this for generating a group of layers or the following choropleth example

var breaks = [0, 4, 16, 64, 256, 1024, 4096, 16384, 65536]

// for each level, we set the filter to choose features with population
// density values between two consecutive values from the scale
for (var p = 0; p < breaks.length; p++) {
  var filters
  if (p < breaks.length - 1) {
    filters = [ 'all',
      [ '>=', 'pop_density', breaks[p] ],
      [ '<', 'pop_density', breaks[p + 1] ]
    ]
  } else {
    filters = [ 'all',
      [ '>=', 'pop_density', breaks[p] ]
    ]
  }
  choroStyle.layers.push({
    id: 'counties-pop-' + p,
    type: 'fill',
    source: 'us-counties',
    'source-layer': 'counties',
    paint: {
      'fill-color': '#5b6b6b',
      // set the opacity based on the level
      'fill-opacity': (p + 1) / breaks.length
    },
    filter: filters
  })
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.