Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leaflet: Pass an extra argument to L.geoJson options

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..?

like image 709
Anton Avatar asked Nov 13 '22 11:11

Anton


1 Answers

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.

like image 98
geoSAM Avatar answered Nov 15 '22 07:11

geoSAM