I'm trying to create a chloropleth using Leaflet, inspired by the official Leaflet documentation, but I've been having some trouble in achieving this, I think due to how my data is structured.
I have a javascript object which has been drawn from a PostGIS database and stored in a dictionary object elsewhere in my project. The following code is used to display the chloropleth when a button is toggled on the website:
function getColor(d,range) {
return d === null ? '#FFFFFF':
d > range[6] ? '#800026' :
d > range[5] ? '#BD0026' :
d > range[4] ? '#E31A1C' :
d > range[3] ? '#FC4E2A' :
d > range[2] ? '#FD8D3C' :
d > range[1] ? '#FEB24C' :
d > range[0] ? '#FED976' :
'#FFEDA0' ;
}
function onDataLayerToggled(params) {
dataLayer = geoDataLayers.find( layer => layer.type == params['dssOverlay'] );
var range = [500,1000,2000,3000,4000,5000,6000];
for (i=0;i<dataLayer.layer.options.data.length; i++) {
dataLayer.layer.setStyle({
fillColor: getColor(dataLayer.layer.options.data[i]['total'], range),
weight: 2,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.7
});
}
dssMap.addLayer( dataLayer.layer );
The structure of the data section of dataLayer
(the bit I'd like to assign colours to) is as follows:
Array(22): [{...}, {...}, {...}, ....]
, where inside each dictionary is the following:
aimag_code: 181
camel: 8.11
cattle: 224.995
goat: 1338.223
horse: 236.749
period: 2020
sheep: 1799.761
total: 3607.838
When I try to use the above code to assign a colour to the "total" field in each dictionary, it assigns the last RGB code to every value in the array. When I try to implement this in the same way as shown in the leaflet documentation (using the code snippet below), the same result happens.
dataLayer.layer.setStyle({
fillColor: getColor(dataLayer.layer, range),
....
}
I've been searching around for a solution all day and haven't managed to find something to fix this yet.