4

I have an leaflet map with 2 geojson file loaded locally using the leaflet ajax filter. I am trying to filter the second geojson (polyline) based on 'click' of any of the first geojson point feature. both of them had the same SiteID field I am able to get the feature ID,

           layer.on("click", function(e){ 
                 pollid= feature.properties.SiteID; // ID from first layer geojson


                 console.log(pollid);

                lyrSpider.addTo(map); // second geojson file 
                console.log(pollid);
            });

how can I pass the (pollid) to filter the second geojson

 function spiderfilter(feature) {


            if (feature.properties.SiteID == pollid) return true; // problem,
        }

I could not figure out the variable scope. here.

1
  • "I solved it by just removing the geojson layer if its exist. if(map.hasLayer(lyrSpider)){ lyrSpider.remove(); }" I couldn't able to achieve this function.. Any samples please? Commented Jun 23, 2020 at 6:49

1 Answer 1

2

If you can create lyrSpider inside of the first function you showed, then you can set the filter option during creation like this:

layer.on("click", function(e){ 
    let pollid = feature.properties.SiteID;

    let lyrSpider = L.geoJSON(geoJSON_data, {
        filter: function(feature, layer) {
            if (pollid == feature.properties.SiteID) {
                return true;
            }
        }
    });

    lyrSpider.addTo(map);
});

See the L.geoJSON docs: http://leafletjs.com/reference-1.3.0.html#geojson-filter.

7
  • Thank you, that was a fantastic solution so far, how can I remove the filter on the second click, , Thanks Commented Apr 20, 2018 at 19:38
  • I don't know the context, but you could create a global variable (clicked) set to (false), add (&& clicked == false) to the condition, and then inside the filter, after the if-statement, set (clicked) to (true). So, after the first click, it will filter no more. Commented Apr 20, 2018 at 20:11
  • Thank you, Actually I don't need to stop the filter I need to update the filter by clicking another point in my first layer, and remove the old filter results. Commented Apr 20, 2018 at 21:14
  • how can I update the filter (re filter by adding new one and removing previous one. Commented Apr 24, 2018 at 13:24
  • 1
    I solved it by just removing the geojson layer if its exist. if(map.hasLayer(lyrSpider)){ lyrSpider.remove(); }. thank you for your help Commented Apr 25, 2018 at 5:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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