Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a parameter to oneachfeature leaflet

I am trying to pass a parameter to bind it with click on a polygon, I have the following:

var mapLayer = new L.TopoJSON(jsonMap, {style: style, onEachFeature: onEachFeature.bind(null,null,selectionManager), pane:'borders'}).addTo(this.map); 


 function onEachFeature(feature, layer, selectionManager) {
                    console.log(selectionManager)
                    layer.on({
                        mouseover: highlightFeature,
                        mouseout: resetHighlight,
                        click: dataFilter.bind(null,ID)
                    });
                }

 function dataFilter(selectionManager,e){
                    var layer = e.target;
                    var zoneName = layer.feature.properties.Index;
                    console.log(zoneName)
                    console.log(selectionManager);
                }

So my goal here is to read a parameter in dataFilter (which is in this case selectionManager)

like image 819
skizofre3e Avatar asked Jan 29 '23 11:01

skizofre3e


1 Answers

As per the Leaflet docs, onEachFeature needs to be a function that receives two parameters (feature and layer). Using Function.prototype.bind in the way you're using it does not do what you want.

Instead, create a closure:

function onEachFeatureClosure(dataFilter) {
    return function onEachFeature(feature, layer) {
        // Your own logic, that uses dataFilter as well as feature and layer
    }
}

L.topoJSON(jsonMap, {
     style: style, 
     onEachFeature: onEachFeatureClosure(selectionManager),
     pane:'borders'
}).addTo(this.map);

Note that the return value from onEachFeatureClosure(selectionManager) is a function which looks like function onEachFeature(feat, layer) {...}.

like image 133
IvanSanchez Avatar answered Feb 03 '23 06:02

IvanSanchez