Search code examples
javascriptajaxleafletturfjs

turf.js: Buffer executing but geojson not being added to leaflet map


div id called buffer. when user clicks on buffer the incidences points get buffered 1 mile

<div id="map2" class="col-md-4 well">
    <p>GeoDjango is da bomb</p>
    <button id="Highlands" class="form-control btn-primary">Highlands</button>
    <button id="buffer" class="form-control btn-warning">Buffer</button>
</div>

javascript

var incidences = new L.GeoJSON.AJAX("http://127.0.0.1:8000/incidence_data/", {
    onEachFeature: function (feature, layer) {
        //console.log(feature.properties);
        layer.bindPopup(feature.properties.name.toString())
    }
});
incidences.addTo(map);

var incidences2 = incidences.toGeoJSON();


$("#buffer").click(function () {
    if ($("#buffer").html() == 'Buffer') {
        var buff = turf.buffer(incidences2, 1, {'units': 'miles'});
        bufferLayer = L.geoJSON(buff).addTo(map);
        $("#buffer").html("Remove Buffer");
    } else {
        map.removeLayer(bufferLayer);
        $("#buffer").html("Buffer");
    }
});

I am not sure if the buffer is executing because there is absolutely nothing in the console.

I found this question which is eerily similar to mine. https://gis.stackexchange.com/questions/285077/does-turf-js-work-with-geodjango


Solution

  • incidences2 should be created only AFTER incidences is fully loaded.

    As a first check try creating it a little later:

    console.log("starting...");
    
    const incidences = new L.GeoJSON.AJAX("http://127.0.0.1:8000/incidence_data/", {
        onEachFeature: function (feature, layer) {
            //console.log(feature.properties);
            layer.bindPopup(feature.properties.name.toString())
        }
    });
    incidences.addTo(map);
    
    console.log("... not loaded yet!");
    
    $("#buffer").click(function () {
        const incidences2 = incidences.toGeoJSON();
        console.log(incidences2);
        if ($("#buffer").html() == 'Buffer') {
            var buff = turf.buffer(incidences2, 1, {'units': 'miles'});
            console.log(buff);
            bufferLayer = L.geoJSON(buff).addTo(map);
            $("#buffer").html("Remove Buffer");
        } else {
            map.removeLayer(bufferLayer);
            $("#buffer").html("Buffer");
        }
    });