Search code examples
javascriptpython-3.xleafletgeojsonfolium

How to customize leaflet style function to get color depending on properties values


I have a dimension called length on geojson properties. I have a drop down list and want to filter by length for example and get different layers colors.

function getColor_by_length(d){
    return d > 9 ? '#800026' :
           d > 5 ? '#BD0026' :
           d > 3 ? '#E31A1C' :
           d > 0 ? '#FC4E2A' :
                   '#FFEDA0';
}

function linkDropDown(){
    var linkSelector = document.getElementById('linkSelector')    
    if (linkSelector.value == "length"){
        geo_json_layer.eachLayer(function (layer) {
            layer.setStyle({fillColor: getColor_by_length(layer.feature.properties.length)})
        });
    }

I always get only one and same color for all my layer. I couldn't figure out where I am wrong. Any idea please?


Solution

  • getColor_by_length doesn't actually return anything. Calling getColor_by_length(something) is always undefined. You need to do this:

    function getColor_by_length(d){
      return d > 9 ? '#800026' :   // <----- return the value
             d > 5 ? '#BD0026' :
             d > 3 ? '#E31A1C' :
             d > 0 ? '#FC4E2A' :
                     '#FFEDA0';
    }
    

    That should do it for you. Assuming the arguments for d are what you think they are.