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

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.

  • Thank you, that was a fantastic solution so far, how can I remove the filter on the second click, , Thanks – user2722043 Apr 20 '18 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. – animehistrionics Apr 20 '18 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. – user2722043 Apr 20 '18 at 21:14
  • how can I update the filter (re filter by adding new one and removing previous one. – user2722043 Apr 24 '18 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 – user2722043 Apr 25 '18 at 5:56

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.