I'm working on choropleth maps using Leaflet framework. I'd like to have several separate layers for several years, so i' ve written this code (note that only names of 'style2002' and 'style2010' should be passed, without any arguments):
population2002 = L.geoJson(regionData, {
style: style2002
});
population2010 = L.geoJson(regionData, {
style: style2010
});
, there "style" functions which are colouring my vector polygons depening on their attributes (which names are prefix 'Pop_' plus year) are:
function style2002(feature)
{
return {
fillColor: getColor(feature.properties.Pop_2002),
weight: 2,
opacity: 1,
color: 'white',
dashArray: '',
fillOpacity: 0.7
};
}
function style2010(feature)
{
return {
fillColor: getColor(feature.properties.Pop_2010),
weight: 2,
opacity: 1,
color: 'white',
dashArray: '',
fillOpacity: 0.7
};
};
As you can guess, i want to use one "style" function instead of separate functions for each year i need. Something like:
function styleByYear(feature, year)
{
var property = 'feature.properties.Pop_';
property += year;
return {
fillColor: getColor(property),
weight: 2,
opacity: 1,
color: 'white',
dashArray: '',
fillOpacity: 0.7
};
}
But how to pass the second argument to style function? In L.geoJson constructor i write only the name of function, without any arguments, as you can see from the first piece of code! What should i do? And one more question: how the first argument ('feature') is passed into layer constructor..?
What if you create a global variable:
var property = 'Pop_' + year
and the edit your function to the following(You should use brackets instead of dot notation):
function styleByYear(feature)
{
return {
fillColor: getColor(feature['properties'][property]),
weight: 2,
opacity: 1,
color: 'white',
dashArray: '',
fillOpacity: 0.7
};
}
I have done something similar to what you're asking based on choropleth tutorial like you. I have multiple buttons that changes map style for different dates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With