intersections method

FeatureCollection intersections(
  1. LineString other
)

Returns a FeatureCollection of Points where the LineString intersects with the LineString other. If the LineStrings do not intersect, an empty FeatureCollection is returned.

Example:

LineString([Coordinate(1, 2), Coordinate(3, 4)]).intersections(LineString([Coordinate(2, 3), Coordinate(4, 5)])); // FeatureCollection([]) - does not intersect
LineString([Coordinate(1, 2), Coordinate(3, 4)]).intersections(LineString([Coordinate(3, 4), Coordinate(1, 2)])); // FeatureCollection([Point()]) - intersects at (2, 3)

Implementation

FeatureCollection intersections(LineString other) {
  Point? lineSegmentsIntersect(LineString segment1, LineString segment2) {
    final double deltaX1 =
        segment1.coordinates.last.x - segment1.coordinates.first.x;
    final double deltaY1 =
        segment1.coordinates.last.y - segment1.coordinates.first.y;

    final double deltaX2 =
        segment2.coordinates.last.x - segment2.coordinates.first.x;
    final double deltaY2 =
        segment2.coordinates.last.y - segment2.coordinates.first.y;

    final double s = (-deltaY1 *
                (segment1.coordinates.first.x -
                    segment2.coordinates.first.x) +
            deltaX1 *
                (segment1.coordinates.first.y -
                    segment2.coordinates.first.y)) /
        (-deltaX2 * deltaY1 + deltaX1 * deltaY2);
    final double t = (deltaX2 *
                (segment1.coordinates.first.y -
                    segment2.coordinates.first.y) -
            deltaY2 *
                (segment1.coordinates.first.x -
                    segment2.coordinates.first.x)) /
        (-deltaX2 * deltaY1 + deltaX1 * deltaY2);

    if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
      return Point(Coordinate(segment1.coordinates.first.x + (t * deltaX1),
          segment1.coordinates.first.y + (t * deltaY1)));
    } else {
      return null;
    }
  }

  List<Point> points = [];

  for (final segment1 in segments) {
    for (final segment2 in other.segments) {
      final intersection = lineSegmentsIntersect(segment1, segment2);
      if (intersection != null) {
        points.add(intersection);
      }
    }
  }

  return FeatureCollection(points);
}