Reputation: 1085
I have a large map layer in which each feature has separate properties for each week of the year. On a button click, I want to style each feature with the mean of the selected properties.
Here is a reproducible example: https://codepen.io/leol222/pen/JjNKEpZ
In this example, I have 'selected' to calculate the mean of properties week1
, week2
, and week3
on button click. I can roughly achieve what I want with a Mapbox expression that creates the variable mean
by summing each week property value with get
and dividing by the number of weeks I have selected:
const colors = [0, '#FCCE25', 2, '#EC7754', 5, '#9B179F', 12, '#0D0887'];
const selectedWeeks = ['week1', 'week2', 'week3'];
const expression = selectedWeeks.map(wk => ['get', wk]);
// ['get', 'week1'], ['get', 'week2'], ['get', 'week3']
document.getElementById('btn').addEventListener('click', () => {
map.setPaintProperty('shapes', 'fill-color',
['let', 'mean', ['/', ['+', ...expression], expression.length],
['interpolate', ['linear'], ['var', 'mean'], ...colors]
]
)
});
The problem I have with this expression is that some features do not include all of the selected week properties. In these features, the ['get', <selected week>]
expression returns null, which then calculates the mean as null, as shown by the black styled squares below:
The black squares are features that do not include all 3 selected weeks of data. What I want my expression to do is to calculate the mean for all of the features by omitting any missing properties. So in this case, features 2 would simply omit the missing week1
property and instead calculate the mean of week2
and week3
, resulting in a new mean
var of 10.5.
Upvotes: 0
Views: 521
Reputation: 181
Only hit on the way :
It should be adapted, but instead of using ['get', propertyName]
you could generate it with an expression such as
const getPropertyValue = propertyName => [
'case',
['boolean', ['has', propertyName], true],
['get', propertyName],
0
];
which here use the property value if it exist or 0 otherwise. -> should be changed for the mean, not sure how yet.
Upvotes: 0