[GIS] Using Leaflet Turf.js to count number of points within buffer

countleafletturf

I would like to count the number of points within the buffer. The draggable marker and buffer seems to work fine but the point count within the buffer doesn't give the correct result with the console log. I would like to put the count result into an information div. I can't work out why the count isn't working.

var map = L.map('map', {
    layers: [osmMap] // only add one!
})
.setView([54.655078, -6.969706], 9);

L.control.defaultExtent().addTo(map);


var baseLayers = {
"OSM Mapnik": osmMap,
"Topography": topoMap,
"Landscape": landMap
};

L.control.layers(baseLayers).addTo(map);

var osmGeocoder = new L.Control.OSMGeocoder({
        collapsed: 'true',
        position: 'topleft',
        text: 'My Area',
        });
    map.addControl(osmGeocoder);


var markers = L.markerClusterGroup({ disableClusteringAtZoom: 14 });

var SportIcon = L.Icon.extend({
    options: {
        iconSize:     [38, 95],
        iconAnchor:   [22, 94],
        popupAnchor:  [-3, -76]
    }
});




var active_places = L.geoJson(active, {
    pointToLayer: function (feature, latlng) {
        var smallIcon = L.icon({
            iconSize: [27, 27],
            iconAnchor: [13, 27],
            popupAnchor: [1, -24],
            iconUrl: 'data/icons/' + feature.properties.Type + '.png'
        });
        return L.marker(latlng, {icon:smallIcon});
    },

    onEachFeature: function (feature, layer) //functionality on click on feature
        {

        layer.bindPopup("Name: " + feature.properties.Name + '</b><br>' + "Council: " + feature.properties.Council + '</b><br>' + "Ownership: " + feature.properties.Ownership + '</b><br>' + "Type: " + feature.properties.Type); //Active Places information
        }
    }).addTo(markers.addTo(map));

// Open popups on hover
active_places.on('mouseover', function(e) {
e.layer.openPopup();
});

function cycleRoutes (d) {
        switch (d) {
            case 'NCN 9': return "Belfast to Slieve Gullion";
            case 'NCN 91': return "Belfast to Ballyshannon";
            case 'NCN 92': return "Ballinamallard to Derry";
            case 'NCN 93': return "Derry to Bangor";
            case 'NCN 94': return "Loughshore Trail";
            case 'NCN 95': return "Tynan to Pettigo";
            case 'NCN 96': return "Toome to Coleraine";
            case 'NCN 97': return "Glenarm to Randalstown";
            case 'NCN 99': return "Strangford Lough to Downpatrick";
            default: return "Unknown";
        }
    };

var cycleNetworks = L.geoJson(routes, {
        style: function(feature) {
            return {
                color: "#ff0000",
                weight: 4,
                opacity: 0.8
            }
        },
        onEachFeature: function (feature, layer) //functionality on click on feature
        {

        layer.bindPopup("Route: " + feature.properties.Route + '</b><br>' + "Description: " + cycleRoutes(feature.properties.Route)); //Network information
        }
    });


var overlayMaps = { //put all overlay layers into one variable container
        "National Cycle Networks": cycleNetworks
    };


    L.control.layers(overlayMaps).addTo(map); // add vector layers to map


var searchControl = new L.Control.Search({
    layer: markers,
    propertyName: 'Name',
    propertyLoc: ['lat', 'lon'],
    //marker: L.CircleMarker([0,0], {radius: 2000, opacity: 1, weight: 1, fillOpacity: 0.4}),
    marker: L.circle([0,0], {radius: 2000, opacity: 1, weight: 1, fillOpacity: 0.4}),
    text: 'Search Facilities',
    zoom: 10,

});


searchControl.on('search_locationfound', function(e) {



    e.layer.setStyle({fillColor: '#3f0', color: '#0f0', radius: '2000'});
    }).on('search_collapsed', function(e) {
        markers.resetStyle(layer);
    });


map.addControl( searchControl );  //inizialize search control

 //add marker that is draggable
    var marker = L.marker(new L.LatLng(54.353218, -6.653019), {
        icon: L.icon.mapkey({
            icon:"home",
            color:'#ffffff',
            background:'#0000ff',
            size:30}),
        draggable: true
    });

    //add marker popup
    marker.bindPopup('This marker is draggable! Move it around to see the Active Places within 1 mile of your area".');
    marker.addTo(map);


    //remove old buffers (used when marker is dragged)
    function removeBuff(){
        map.removeLayer(buff);
        };



    //create buffer (used when the marker is dragged)
    function updateBuffer(){
        //Make the marker a feature
        var pointMarker = marker.toGeoJSON();
        //buffer the marker geoJSON feature
        var buffered = turf.buffer(pointMarker, 1, 'miles');
        //add buffer to the map. Note: no "var" before "buff" makes it a global variable and usable within the removeBuff() function. 
        buff = L.geoJson(buffered);
        buff.addTo(map);
        console.log(buffered); //added part for counting points within buffer
        var pt = active_places.toGeoJSON();
        var countPt = turf.count(buffered, pt, 'description');
        console.log(countPt);
        var resultFeatures = pt.features.concat(countPt.features);
        var result = {
            "type": "FeatureCollection",
            "features": resultFeatures
        };
    };
    marker.on('drag', function(){removeBuff(), updateBuffer()});
    updateBuffer();


var legend = L.control({position: 'bottomright'});
legend.onAdd = function (map) {
    var div = L.DomUtil.create('div', 'info legend');
    div.innerHTML += '<img src="data/icons/adventure.png" i class="legend i" style="background" <span style="font-weight: 600;">Adventure Sport</span><br>' +
    '<img src="data/icons/Athletics.png" i class="legend i" style="background" <span style="font-weight: 600;">Athletics Track</span><br>' +
    '<img src="data/icons/bowls.png" i class="legend i" style="background" <span style="font-weight: 600;">Bowling Green</span><br>' +
    '<img src="data/icons/Court.png" i class="legend i" style="background" <span style="font-weight: 600;">Court</span><br>' +
    '<img src="data/icons/golfing.png" i class="legend i" style="background" <span style="font-weight: 600;">Golf Course</span><br>' +
    '<img src="data/icons/gym.png" i class="legend i" style="background" <span style="font-weight: 600;">Gymnasium</span><br>' +
    '<img src="data/icons/soccerfield.png" i class="legend i" style="background" <span style="font-weight: 600;">Playing Pitch</span><br>' +
    '<img src="data/icons/arena.png" i class="legend i" style="background" <span style="font-weight: 600;">Sports Hall</span><br>' +
    '<img src="data/icons/swimming.png" i class="legend i" style="background" <span style="font-weight: 600;">Swimming Pool</span><br>' +
    '<img src="data/icons/waterskiing.png" i class="legend i" style="background" <span style="font-weight: 600;">Water Sport</span><br>';
    return div;
};


legend.addTo(map);

var homepagebutton = new L.Control.Button(L.DomUtil.get('homepage'), { toggleButton: 'active' });
homepagebutton.addTo(map);
homepagebutton.on('click', function () {
window.location.href = 'https://ecocommni.github.io/BootstrapTest/'
});

sidebar = L.control.sidebar('helpsidebar', { position: 'right' });
sidebar.addTo(map);

helpButton = new L.Control.Button(L.DomUtil.get('helpbutton'), { toggleButton: 'active' });
helpButton.addTo(map);
helpButton.on('click', function () {
if (helpButton.isToggled()) {
    sidebar.hide();
} else {
    sidebar.show();
}
});

Best Answer

I used a different method with Turf:

    var shape2 = allPoints.toGeoJSON()
    var ptsWithinbuff = turf.within(shape2, buffered.toGeoJSON());
    alert('Found ' + ptsWithinbuff.features.length + ' features');