0

I am trying to make a leaflet layer that will listen to a slider bar and change the colour of all its features based on if a property of each feature meets a certain criterion.

I begin by getting the event:

$( "#time-slider-bar" ).on("slidechange", function() {

and then I try to change the style on each feature like so:

        thresholdLayer.eachLayer(function (layer) {

            var year = $("#time-slider-bar").slider("option", "value");

            console.log("_yr"+year);
            console.log(layer.feature.properties["_yr"+year]);

            return layer.setStyle(function(layer) {

                console.log("does not print");

                if (layer.feature.properties["_yr"+year] > 100) {
                    return {
                        fillColor: "#ff0000",
                        fillOpacity: 1
                    };
                } else {
                    return {
                        fillOpacity: 0
                    };
                }
            })
        })

But then nothing happens. The console.log("does not print"); statement does just that - doesn't print. For some reason, layer.setStyle is not executing. Am I not using this function correctly? I am following a previous example where I changed an icon on a different layer:

        markerLayer.eachLayer(function (layer) {
            return layer.setIcon(L.icon({
                iconUrl: 'svg/' + $("#time-slider-bar").slider("option", "value") + '/' + layer.feature.properties.name + '.svg'
            }))
        });

Which works just fine.

2

You can try this: call 'layer.setStyle' (don't return it), then use another function to build the options object, feeding it the 'year' variable...

Here is a JS Bin with an example (it listens for a button-click): https://jsbin.com/hobohah/2/edit?html,js,console,output

And here I tried to write out the code using your variable names and styling options:

$( "#time-slider-bar" ).on("slidechange", function() {

      var year = $("#time-slider-bar").slider("option", "value");

      thresholdLayer.eachLayer(function (layer) {

          // don't return layer.setStyle-- just call it. 
          // the setStyle method expects an object. 
          // we can use another function to build and return that object, if we feed it the 'year' value. 

          layer.setStyle(getStyle(year));
      }
}

function getStyle(y){
    if (y > 100) {return {fillColor: "#ff0000", fillOpacity: 1}}
    else {return {fillOpacity: 0}}
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.