[GIS] Control to select data source on Leaflet map

javascriptjsonleaflet

I am building a map using leaflet.

My data source looks something like this:

var districts = 
{"type": "FeatureCollection", "features": 
[

{"type":"Feature",
"geometry":
{"type":"MultiPolygon","coordinates":[[[ [-75.228404,40.084708],[-75.2286,40.084875],[-75.230501,40.086024]//...
]]] 
},
"properties":{"dist_num":"8", "gender":"M", "party":"democrat"}},


{"type":"Feature",
"geometry":
{"type":"MultiPolygon","coordinates":[[[ [-75.227985,40.084356],[-75.2281,40.0843],[-75.228241,40.084198],//...
]]] 
},
"properties":{"dist_num":"5", "gender":"F", "party":"republican"}}, //....

];

I've got a working map that shows districts by party (democrat/republican) using this javascript:

var map = L.map('map').setView([39.955, -75.1647], 11);

L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
    maxZoom: 18
}).addTo(map);

var geojson;

function getColor(d) {
    return d == 'Democrat' ? 'blue' :
           d == 'Republican'  ? 'red':
              '#FFEDA0';
}

function style(feature) {
    return {
        fillColor: getColor(feature.properties.party),
        weight: 2,
        opacity: 1,
        color: 'white',
        dashArray: '3',
        fillOpacity: 0.3
    };
}

L.geoJson(districts, {style: style}).addTo(map);

Now I want to add a control where the user can switch from the fillColor in the function style from political party to display by gender. Does Leaflet have a built in method to do this? Or do I need to build my own in HTML/Javascript/Jquery?

Best Answer

You can change your style function to accept another parameter, and use that to set your style. When the user wants to change the rendering, you just call .setStyle(feature, color). You will also need to create a function to define the colors for that dataset as well. For example, I'm using a function name of getGenderColor().

Example:

function style(feature, fillColor) {
    return {
        fillColor : fillColor,
        ....
    }
}
var geojson = L.geoJson(districts, {style: function (f) {
    return style(f, getColor(f.properties.party));
}}).addTo(map);

$("#button-to-render").on('click', function () {
    geojson.setStyle(function (f) {
        return style(f, getGenderColor(f.properties.gender));
    });
});

There are other ways to do this, but I think this example will work for what you need.

I created a simple example in jsfiddle: http://jsfiddle.net/TnX96/103/