[GIS] turfjs intersect line and polygon

intersectionturf

In old turfjs versions, it was possible to intersect a line and a polygon, like in this example.

But changing the turf.js version to the last one makes it fail, as shown in this other example.

The docs say that the intersect function works only with two polygons, so the error is documented.

Is it possible to use some other function to do that? Is there any example around there showing how to do it?

Best Answer

==EDIT==

A better soulution, that works with multilinestrings and multiple intersections, is using lineSplit, as shown in this example. Just iterate through the splitted lines and take only one each two of them.


I found the answer, which is combining lineIntersect and lineSlice:

let intersectionPoints = turf.lineIntersect(line, poly);
let intersectionPointsArray = intersectionPoints.features.map(d => {return d.geometry.coordinates});

let intersection = turf.lineSlice(turf.point(intersectionPointsArray[0]), turf.point(intersectionPointsArray[1]), line);

As I mention in the example, this will work with only one part of the line intersecting the polygon. If the line goes in and out several times, the method must be applied as many times as needed.

Related Question