3

I am trying to create a buffered line layer by creating GeoJSON line string from routing line and buffering it with turf.js and then show it on the map.

Here is my code:

route.on('routeselected', function(e) {
    var r = e.route;
        var lineCoordinates = [],
            i,
            latLng;
        for (i = 0; i < r.coordinates.length; i++) {
            latLng = L.latLng(r.coordinates[i]);
            lineCoordinates.push([latLng.lng, latLng.lat]);
        }

        let lineString = L.polyline(lineCoordinates,{color: 'black'});
        var buffered = turf.buffer(lineString, 500, {units: 'miles'});
        var bufferedLayer = L.geoJSON(null);
        bufferedLayer.addData(buffered);
        bufferedLayer.addTo(map);
        });

Any suggestion?

1 Answer 1

2

turf.buffer method returns GeoJSON feature, which cannot be directly added to the map. You have to create GeoJSON layer, add feature to the layer and layer to the map. Leaflet polyline also has to be converted to GeoJSON to be used as input to turf.buffer method.

Code could then look something like this:

var buffered = turf.buffer(lineString.toGeoJSON(), 500, {units: 'miles'});
var bufferedLayer = L.geoJSON(null);
bufferedLayer.addData(buffered);
bufferedLayer.addTo(map);
2
  • Hey, thanks for your suggestion. I am getting "Uncaught Error: Unknown Geometry Type". Should i convert the array to geojson.If yes, then how? Commented Feb 10, 2021 at 15:17
  • I didn't test it, so I overlooked that Leaflet polyline has to be converted to GeoJSON for turf.js. See corrected answer.
    – TomazicM
    Commented Feb 10, 2021 at 16:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.