linesIntersectAsMap method

Map<bool, Intersection> linesIntersectAsMap(
  1. Coordinate a0,
  2. Coordinate a1,
  3. Coordinate b0,
  4. Coordinate b1,
)

Implementation

Map<bool, Intersection> linesIntersectAsMap(JTS.Coordinate a0,
    JTS.Coordinate a1, JTS.Coordinate b0, JTS.Coordinate b1) {
  Intersection intersection;
  // returns false if the lines are coincident (e.g., parallel or on top of each other)
  //
  // returns an object if the lines intersect:
  //   {
  //     pt: [x, y],    where the intersection point is at
  //     alongA: where intersection point is along A,
  //     alongB: where intersection point is along B
  //   }
  //
  //  alongA and alongB will each be one of: -2, -1, 0, 1, 2
  //
  //  with the following meaning:
  //
  //    -2   intersection point is before segment's first point
  //    -1   intersection point is directly on segment's first point
  //     0   intersection point is between segment's first and second points (exclusive)
  //     1   intersection point is directly on segment's second point
  //     2   intersection point is after segment's second point

  var adx = a1.x - a0.x;
  var ady = a1.y - a0.y;
  var bdx = b1.x - b0.x;
  var bdy = b1.y - b0.y;

  var axb = adx * bdy - ady * bdx;
  var n1 = math.sqrt(adx * adx + ady * ady);
  var n2 = math.sqrt(bdx * bdx + bdy * bdy);
  if ((axb).abs() <= eps * (n1 + n2)) {
    intersection = Intersection.Empty;
    return {false: intersection}; // lines are coincident

  }

  var dx = a0.x - b0.x;
  var dy = a0.y - b0.y;

  var A = (bdx * dy - bdy * dx) / axb;
  var B = (adx * dy - ady * dx) / axb;

  JTS.Coordinate pt = JTS.Coordinate(a0.x + A * adx, a0.y + A * ady);
  intersection = new Intersection(alongA: 0, alongB: 0, pt: pt);

  // categorize where intersection point is along A and B

  if (pointsSame(pt, a0))
    intersection.alongA = -1;
  else if (pointsSame(pt, a1))
    intersection.alongA = 1;
  else if (A < 0)
    intersection.alongA = -2;
  else if (A > 1) intersection.alongA = 2;

  if (pointsSame(pt, b0))
    intersection.alongB = -1;
  else if (pointsSame(pt, b1))
    intersection.alongB = 1;
  else if (B < 0)
    intersection.alongB = -2;
  else if (B > 1) intersection.alongB = 2;

  return {true: intersection};
}