Search code examples
javascriptleafletturfjs

Leaflet and Turf.js Points within poly


I have a simple map with 17 points (GeoJSON) in leaflet, and using the draw tool, I create a polygon to use to select the points within th polygon.

map.on('draw:created', function (e) {  //from draw tool
    var type = e.layerType,
        layer = e.layer;
        editableLayers.addLayer(layer);
        GetSelection(editableLayers);
});

function GetSelection(layer){
    var count = allPoints.getLayers().length;
    console.log(count +" Sites");  //says 17
    var drawList = editableLayers.getLayers().length;
    console.log(drawList +" Polys");  //Says 1

    if (editableLayers.getLayers().length >0){
        var fcpt = turf.featurecollection(allPoints);
        console.log(fcpt);  // says 17
        var fcpoly = turf.featurecollection(editableLayers);
        console.log(fcpoly);  // fails as undefined
           //var ptsWithin = turf.within(fcpt,editableLayers);
        var ptsWithin = turf.within(fcpt,fcpoly);
        console.log(ptsWithin);  //never gets this far.

    };
};

Any ideas or suggestions?


Solution

  • turf.featurecollection expects an array of GeoJSON Features, not a Leaflet Layer Group like your allPoints and editableLayers variables.

    Similarly, turf.within expects 2 GeoJSON Feature Collections as arguments, not Leaflet Layer Groups.

    So you could probably try directly:

    var ptsWithin = turf.within(allPoints.toGeoJSON(), editableLayers.toGeoJSON());