0
votes

So far I have a map (MapBox GL) that draws counties with borders.

    map.addSource('states', {
        'type': 'geojson',
        'data': '/geojson/county_boundaries.geojson'
    });

    map.addLayer({ // adding borders:
        'id': 'state-borders',
        'type': 'line',
        'source': 'states',
        'layout': {},
        'paint': {
            'line-color': '#627BC1',
            'line-width': 2
        }
    });

This county_borders.geojson has items (features) with parameter 'name'.

...
   "features": [
       { "type": "Feature", "id": 8, "properties": { "name": "New York", ...

I have another stats.json file with properties for most of the features, where 'name' is the main key.

    "New York": {
        "Population": "500123",
        "Food Consumption Level": "3",
        "Color": "#e67800"
    },

I am new to MapBox, and with so many parameters-based functions I am getting lost. Please help me to change the fill color of all states with the Color from stats.json file by looking up their names ("New York" etc). I suppose I need to iterate through all the features and set their filling somehow.

The only way I have found to fill the states with the same default color is like this:

    map.addLayer({
        'id': 'state-fills',
        'type': 'fill',
        'source': 'states',
        'layout': {},
        'paint': {
            'fill-color': '#627BC1',
            'fill-opacity': [
                'case',
                ['boolean', ['feature-state', 'hover'], false],
                1,
                0.5
            ]
        }
    });

It is working to fill all the states. But not what I need. I would like to dynamically modify color of each state runtime, without changing original geojson file. (Other params in data.json I show in popup, which works fine with this extra file approach.)

1

1 Answers

0
votes

Instead of adding your original GeoJSON file as a source to your map, you can add the stats to the GeoJSON with Javascript before adding the source:

var geojson = addStats(originalGeojson, stats);
map.addSource('states', {
    'type': 'geojson',
    'data': geojson
});

function addStats(geojson, stats) {
  geojson.features.forEach((feature) => {
    var statsForFeature = stats[feature.properties.name];
    if (statsForFeature) {
      // add stats to the feature's properties
      feature.properties = Object.assign(feature.properties, statsForFeature);
    }
  });

  return geojson;
}

After that, you can use data-driven styling with layer type 'fill' to color your features:

map.addLayer({ // adding borders:
  'id': 'state-borders',
  // use type 'fill'
  'type': 'fill',
  'source': 'states',
  'layout': {},
  'paint': {
    'fill-outline-color': '#627BC1',
    // use data-driven styling
    'fill-color': ['get', 'Color'],
  },
});

Here is a working example demonstrating this technique: https://jsfiddle.net/0s17mqvh/