0

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?

1

==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.

  • 1
    I was playing with JSTS instead. As you seem to work only with Turf, I put the example link just as an addition bl.ocks.org/ThomasG77/d66f1040960646abf56c90ae5e759b8a – ThomasG77 Jul 24 '18 at 14:23
  • @ThomasG77 Thank you. It works better. I'm trying to use it with ES6 but I can't find how. A similar solution like this doesn't work: github.com/DenisCarriere/jsts-es6-example/blob/master/… – Roger Veciana Jul 25 '18 at 12:48
  • 1
    Try codesandbox.io/s/0m4mj899rv Same version as before but ES6 based (took some shortcuts but enough for the demonstration) – ThomasG77 Jul 25 '18 at 15:33
  • The problem is that the import { io } from "jsts"; part doesn't work. All the examples I see use something like import GeoJSONReader from 'jsts/org/locationtech/jts/io/GeoJSONReader', but then, the intersection function does not exist. – Roger Veciana Jul 26 '18 at 9:13
  • 1
    "The problem is that the import { io } from "jsts"; part doesn't work" Not sure why you are saying that. It works on my side (using Google Chrome). For import GeoJSONReader from 'jsts/org/locationtech/jts/io/GeoJSONReader', like you, I was also not able to make it works (I thinkd related to the fact Node vs browser/webpack context) – ThomasG77 Jul 26 '18 at 14:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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