2

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?

Bill Chappell
  • 281
  • 4
  • 20

2 Answers2

2

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());
ghybs
  • 47,565
  • 6
  • 74
  • 99
  • I don't have enough points to up vote your answer. I was on the right track this afternoon but was having trouble finding the right code, you had the simple fix. Thanks. – Bill Chappell Mar 16 '16 at 18:52
2

@ghybs was right, it was a difference between Leaflet and turf, while the points were OK, the polygon did not come over. Passing turf the GeoJson the polygon info allowed it to work.

Working copy:

map.on('draw:created', function (e) {
    featureGroup.clearLayers();
    layer = e.layer;
    featureGroup.addLayer(layer);
    GetSelection(featureGroup);
});

function GetSelection(layer){

    var shape2 = allPoints.toGeoJSON()  //All facilities
    var ptsWithin = turf.within(shape2, layer.toGeoJSON());

        alert('Found ' + ptsWithin.features.length + ' features');  
        alert("results "+JSON.stringify(ptsWithin));
};
Bill Chappell
  • 281
  • 4
  • 20