Search code examples
javascriptleafletturfjs

Return Leaflet GeoJSON polygons that intersect a point with Turf JS library


Leaflet and Turf. I am trying find all the layers on a Leaflet map that intersect a point when the user clicks on the map. I am using the turf library to test for this. In the console when I click on the map it returns this error:

var c = new L.GeoJSON.AJAX("http://127.0.0.1:8000/childcare_buff_data/",{
        style: color(c, "orange", 0.8)})
        ;
    c.addTo(map);

    map.on('click',function(e){
        lat = e.latlng.lat;
        lon = e.latlng.lng;
        ProcessClick(lat,lon)
    });

    var theMarker;
    var a;

    function ProcessClick(lat,lon){
        theMarker = L.marker([lat,lon]).addTo(map);
        c.eachLayer(function(layer) {
            intersects=turf.intersect(theMarker.toGeoJSON(),layer.toGeoJSON());
            if (intersects){
                a=layer.feature.properties.buff
                console.log(a);
                }
            })};

I get this error

turf.min.js:1 Uncaught TypeError: Cannot read property 'length' of null
    at turf.min.js:1
    at turf.min.js:1
    at S (turf.min.js:1)
    at Pn (turf.min.js:1)
    at Object.Lo [as intersect] (turf.min.js:1)
    at js2.js:31
    at eachLayer (leaflet.js:5)
    at ProcessClick (js2.js:30)
    at e.<anonymous> (js2.js:22)
    at e.fire (leaflet.js:5)

enter image description here

here is the geojson http://www.mediafire.com/file/9fnbz32ib9n1aaj/childcare.geojson/file

UPDATE

by using

turf.booleanWithin(theMarker.toGeoJSON(),geom.toGeoJSON());

i get

turf.min.js:1 Uncaught Error: coordinates must only contain numbers
    at Y (turf.min.js:1)
    at Y (turf.min.js:1)
    at U (turf.min.js:1)
    at Pt (turf.min.js:1)
    at Object.Cn [as booleanWithin] (turf.min.js:1)
    at js2.js:33
    at eachLayer (leaflet.js:5)
    at ProcessClick (js2.js:31)
    at e.<anonymous> (js2.js:22)
    at e.fire (leaflet.js:5)

Solution

  • intersect expects two polygons as its parameters but you're feeding it a point hence a missing length property :

    Takes two polygons and finds their intersection

    Try turf.booleanWithin(theMarker.toGeoJSON(), layer.toGeoJSON()) instead:

    Boolean-within returns true if the first geometry is completely within the second geometry.