0
votes

I'm making a choropleth map with Mapbox that changes according to a user-defined day. The color is based on the prob for a given day. For now, I'm passing prob1 ... prob10 as properties in a geojson, but I would prefer to have a single prob property that contains an object that I can subset.

//initialize map on day 1
var day = 1;

//prepare color scale
function makeColorScale(d) {
  return ([
    'interpolate', ['linear'],
    ['get', 'prob' + d],        // how to get object property here?
    0, '#440154',
    0.04, '#3B528B',
    0.08, '#21908C',
    0.25, '#5DC863',
    0.4, '#FDE725',
    1, '#696969'
  ])
};


map.addSource('county-data', {
  type: 'geojson',
  data: data
});

map.addLayer({
    'id': 'counties-join',
    'type': 'fill',
    'source': 'county-data',
    'paint': {
      'fill-opacity': 0.3,
      'fill-color': makeColorScale(day)
    }
  }, 'waterway-label' // ensures polygons are rendered above waterway-labels
);

I've tried e.g. modifying to ['get', 'prob.1'] while adding the object prob: {'1': 0.05, '2':0.01}; to my geojson, but that doesn't work.

1
Please include your actual code. It's not clear what you mean by "somehow querying".Steve Bennett
I haven't added a full reprex, but do my edits make it clear enough?linden
Btw I think you meant 'object' instead of 'array' so I updated your question.Steve Bennett

1 Answers

0
votes

I have not tried this, but I believe you can access attributes of an object property by using this form of the ['get'] operator:

["get", string, object]: value

So if your features had a prob property that looked like {'1': 0.05, '2': 0.01} then you could write your makeColorScale() function like this:

function makeColorScale(d) {
  return ([
    'interpolate', ['linear'],
    ['get', String(d), ['get', 'prob']],
    0, '#440154',
    0.04, '#3B528B',
    0.08, '#21908C',
    0.25, '#5DC863',
    0.4, '#FDE725',
    1, '#696969'
  ])
};

I think. The ['get', 'prob'] fetches the object, then the ['get', String(d)] looks up the property you want within that object.