Reputation: 2325
This Leaflet.js choropleth example assigns polygon color based on the geoJSON file density values.
function getColor(d) {
return d > 1000 ? '#800026' :
d > 500 ? '#BD0026' :
d > 200 ? '#E31A1C' :
d > 100 ? '#FC4E2A' :
d > 50 ? '#FD8D3C' :
d > 20 ? '#FEB24C' :
d > 10 ? '#FED976' :
'#FFEDA0';
}
This updates each polygon's color in function style(feature)
function style(feature) {
return {
fillColor: getColor(feature.properties.density),
weight: 2,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.7
};
}
and this new style is added to the map
L.geoJson(statesData, {style: style}).addTo(map);
However in my situation, my equivalent of the example's statesData
geoJSON file doesn't have the density value in it.
Instead I have the density values in a separate data file that I used to create new array. This array has state name
values and density values
var my_array = [
['name': 'alabama', 'density': 59],
['name': 'alaska', 'density': 30],
etc
]
The question is how to relate the name
string values in both the geoJSON file and the separate data file so that I can get the associated density values into function style(feature)
to change polygon colors?
This is likely not necessarily a Leaflet.js question but could a general Javascript 'how to' question.
So far I can loop through my_array
and create a new array with name
and color values.
color_array = []
for(var i=0; i < my_array.length; i++) {
color_array.push([my_array[i][0] + ', ' + getColor(my_array[i][1])]);
}
To get new color_array
color_array = [
['alabama', '#FFEDA0'],
['alaska', '#FEB24C'],
etc
]
Now how can I use this new color_array
with the function style(feature)
so that the color is set correctly for each name
?
In SQL I would do a join on name
and feed the name
and related density value to the getColor
function with output being the name
, density and color.
How can that be done in javascript?
Upvotes: 1
Views: 1302
Reputation: 6233
You can probably skip step of creating the color array up front unless you need to cache it for performance reasons.
Just do this:
var my_array = [{
'name': 'alabama',
'density': 59
}, {
'name': 'alaska',
'density': 30
}];
function getColor(density) {
if (density > 30) return 'blue';
return 'red';
}
function getStateColor(stateName) {
var color;
for (var i = 0; i < my_array.length; i++) {
if (my_array[i].name === stateName) {
color = getColor(my_array[i].density);
break;
}
}
return color;
}
alert("alabama = " + getStateColor('alabama'));
Then you can do this
function style(feature) {
return {
fillColor: getStateColor(feature.properties.stateName),
weight: 2,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.7
};
}
Upvotes: 3