Search code examples
leafletmapboxturfjs

Turf.js erase produces polygon with wrong projection


I am using turfjs erase together with the leaflet draw plugin to subtract existing polygons from the new polygon being drawn. However the result polygon does not display correctly on the map and this seems to be a projection issue.

mapEPSG4326.on('draw:created', function (e) {
    var clippedZone = e.layer.toGeoJSON();
    polyLayer2.eachLayer(function (existingPoly) {
        clippedZone = turf.erase(clippedZone, existingPoly.feature);
    });
    polyLayer2.addData(clippedZone);
});

When changing my leaflet map projection CRS to L.CRS.EPSG4326 the polygon displays correctly but this produces other problems.

Is there a way to change the projection of the result polygon from turf.js in order to display correctly on the default L.CRS.EPSG3857 projection used by leaflet?

A jsfiddle showing the behaviour https://jsfiddle.net/pdjo/s5v19es0/3/


Solution

  • What you're most likely seeing is the effect of approximating the line between two points on earth by a straight line in spherical mercator. The real closest line between two points on earth, known as a great circle, will generally not be straight in spherical mercator, but rather appear like a curve. A straight line is a good approximation for short distances, though.

    If you did the same thing on a much smaller area (say a couple of kilometers), it would look great.

    Either do this on a smaller area, or draw lines using some plugin that draws actual great circles.

    To sum up: the error is not in Turf or the data, but rather how Leaflet approximates lines as straight, rather than real great circles (which, IMHO, is a reasonable trade off, but breaks down in cases like this).