0

I have this code where I'm trying to create a buffer dynamically from a draggable marker and then count how many points fall insed this buffer. As of now I can drag the buffer around without any problem and the first position of the buffer return the points count. But when I drag the marker the count does not update and also the buffer ends in a layer above the points. Here is the code:

 //add marker that is draggable
 var marker = L.marker(new L.LatLng(39.702475, -104.875398), {
     draggable: true
 });

 //add marker popup
 marker.bindPopup('This marker is draggable!');
 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
     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);
 };

 marker.on('drag', function () {
     removeBuff(), updateBuffer()
 });
 updateBuffer();

 //geojson call for points
 var data = L.geoJson(traffacc, {
     pointToLayer: function (feature, latlgn) {
         var popupContect = "<b>Accident Year:</b>" + feature.properties.year_STR;
         return L.circleMarker(latlgn, Style(feature)).bindPopup(popupContect);
     },
 }).addTo(map);

var pt = data.toGeoJSON();

 var countPt = turf.count(buffered, pt, 'description');

 console.log(countPt);

var resultFeatures = pt.features.concat(countPt.features);
var result = {
"type": "FeatureCollection",
"features": resultFeatures
};

As you can imagine this code is a patchwork of other people's code. Any ideas of how I can achieve the second part?

0

Your 'var CountPt' part of the code (which does the counting of points) needs to be moved to within the updateBuffer function so that it constantly reruns.

 function updateBuffer() {
     var pointMarker = marker.toGeoJSON();
     buffered = turf.buffer(pointMarker, 1, 'miles');
     buff = L.geoJson(buffered);
     buff.addTo(map);
     console.log(buffered);
     var countPt = turf.count(buffered, pt, 'description');
     console.log(countPt);
 };

Something like this should do the job. At the moment you only run the count once by the looks of it

Perhaps set up a jsfiddle if you need further assistance.

Good luck, Rowan

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.