How to style features depending on comparison operators in Leaflet

Viewed 505

All the examples I find online that talk about how to style a feature depending on one of its properties use a switch statement that evaluates whether that property corresponds to a specific value.

For example this is taken form one of Leaflet's official tutorials:

L.geoJSON(states, {
style: function(feature) {
    switch (feature.properties.party) {
        case 'Republican': return {color: "#ff0000"};
        case 'Democrat':   return {color: "#0000ff"};
    }
}
}).addTo(map);

What if I wanted to determine the feature's color depending on a numeric treshold? Say all features that have propertyX (which is a number) bigger than a certain value get colored red, otherwise blue.

I found this post where one user explains that switch statements are not made for comparisons; how can I do one then?

If use an external function (see code below) the latter seems to not be able to access the feature's properties.

L.geoJSON(states, {
    style: styling
    }).addTo(map);

function styling () {
    if (feature.properties.numericProp > 100) {
        return {color: "red"}
    } else {
        return {color: "blue"}
    }
}
1 Answers
Related