4

I am trying to achieve a buffer similar to Leaflet.buffer on my map. However, Leaflet.buffer seems to be only working with Leaflet.Draw.

I am using Leaflet Editable to draw my layers and I have a polyline I would like to add a buffer to. However, I could not find any plugin that does the job.

I know that I can create a buffer with Turf@buffer:

let lineString = turf.lineString(coordArr);
let bufferedLine = turf.buffer(lineString, 0.5, {units: 'miles'});

but I want it to be similar to Leaflet.buffer so that you can slide the buffer around on the map. (More user friendly)

Is there a way to achieve that by using Turf.js with Leaflet.Editable?

vtCode
  • 71
  • 7

1 Answers1

2

You can do this using Turf.js' buffer module. You create a buffer around your polyline and draw the resulting geojson on a leaflet map. Here is a working example.

var center = [37.78791180770003, -122.40962505340575];

var map = L.map('map').setView(center, 14);;

L.tileLayer(
  'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 18
  }).addTo(map);


var line = {
  "type": "Feature",
  "properties": {
    "color": "blue"
  },
  "geometry": {
    "type": "LineString",
    "coordinates": [
      [-122.40447521209718,
        37.79367718768535
      ],
      [-122.40803718566895,
        37.79171022624846
      ],
      [-122.40769386291502,
        37.79096412372944
      ],
      [-122.40662097930908,
        37.789641468930114
      ],
      [-122.40941047668457,
        37.789675383451495
      ],
      [-122.40992546081543,
        37.78875968591083
      ],
      [-122.40962505340575,
        37.78791180770003
      ]
    ]
  }
};



L.geoJSON(line, {
  style: function(feature) {
    return {
      color: feature.properties.color
    };
  }
}).addTo(map);

var polygon = turf.buffer(line, 0.5, {
  units: 'miles'
});

L.geoJSON(polygon, {
  style: function(feature) {
    return {
      color: feature.properties.color
    };
  }
}).addTo(map);
#map {
  height: 300px;
}
<script src="https://npmcdn.com/@turf/turf/turf.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.5.1/leaflet.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.5.1/leaflet.js"></script>
<div id="map"></div>
WaughWaugh
  • 1,012
  • 10
  • 15