5

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

4

2 回答 2

1

如果你创建一个全局变量怎么办:

var property = 'Pop_' + year

并将您的功能编辑为以下内容(您应该使用括号而不是点符号):

    function styleByYear(feature)
{   

    return {
        fillColor: getColor(feature['properties'][property]),
        weight: 2,
        opacity: 1,
        color: 'white',
        dashArray: '',
        fillOpacity: 0.7
    };
}

根据像您这样的 choropleth 教程,我已经做了类似于您所要求的事情。我有多个按钮可以更改不同日期的地图样式。

于 2013-11-18T16:58:25.647 回答
0

您可以尝试GeoJSON 的 Leaflet 教程中的内容。在“选项”部分中查找第二个代码部分。您只需先添加正常样式(即两年都相同的东西)。取自该站点的示例,添加了您的特定代码:

geojsonlayer = L.geoJson(regionData, {
  style: function(feature) {
    var finalStyleObject = normalStyling(feature); //return the normal style object
    switch (feature.properties) { //switch through the various years
        case 'Pop_2002': {finalStyleObject.fillColor: "#ff0000"};
        case 'Pop_2010': {finalStyleObject.fillColor: "#0000ff"};
    }
    return finalStyleObject;
  }
});

function normalStyling(feature){
  return {
        weight: 2,
        opacity: 1,
        color: 'white',
        dashArray: '',
        fillOpacity: 0.7
    };
}
于 2013-09-17T09:29:29.903 回答