0
votes

There are several tutorials on data-driven styling on Mapbox's site, but none of them address how to update an existing data-driven style (created in Mapbox Studio) in-session. For example, say I want to create a choropleth of US states, colored by area. User then selects 'color by population' and the color of the states update accordingly.

I've found some resources that would allow one to achieve this by adding the geojson of all the states and then doing map.addLayer, however the geojson I'm working with (census tracts) is too massive to add to the front-end, so I needed to change the data-driven styling of an existing layer (or find a similar work-around). The data has to be a persisted tileset from mapbox studio, with user updating the data coloration based on geojson properties.

Any ideas or examples would be much appreciated.

1

1 Answers

2
votes

Updating data-driven styling at run-time is straightforward. You simply call map.setPaintProperty.

I usually implement this with one function that generates the property value. Something like this:

function fillColorByPopulation(min, max) {
    return {
        property: 'pop',
        stops: [
            [min, 'red'],
            [max, 'blue']
        ],
        type: 'exponential'
    }
}
function updateStyle(prop) {
    if (prop === 'population') {
        map.setPaintStyle('regions', 'fill-color', fillColorByPopulation(data.minpopulation, data.maxpopulation));
    } else {
        map.setPaintStyle('regions', 'fill-color', 'transparent');
    }
}

I generally don't create any data-driven styles within Mapbox Studio. It's simpler to create them all in Javascript.