nearestEndpoint static method

Coordinate nearestEndpoint(
  1. Coordinate p1,
  2. Coordinate p2,
  3. Coordinate q1,
  4. Coordinate q2,
)

Finds the endpoint of the segments P and Q which is closest to the other segment. This is a reasonable surrogate for the true intersection points in ill-conditioned cases (e.g. where two segments are nearly coincident, or where the endpoint of one segment lies almost on the other segment).

This replaces the older CentralEndpoint heuristic, which chose the wrong endpoint in some cases where the segments had very distinct slopes and one endpoint lay almost on the other segment.

@param p1 an endpoint of segment P @param p2 an endpoint of segment P @param q1 an endpoint of segment Q @param q2 an endpoint of segment Q @return the nearest endpoint to the other segment

Implementation

static Coordinate nearestEndpoint(
    Coordinate p1, Coordinate p2, Coordinate q1, Coordinate q2) {
  Coordinate nearestPt = p1;
  double minDist = Distance.pointToSegment(p1, q1, q2);

  double dist = Distance.pointToSegment(p2, q1, q2);
  if (dist < minDist) {
    minDist = dist;
    nearestPt = p2;
  }
  dist = Distance.pointToSegment(q1, p1, p2);
  if (dist < minDist) {
    minDist = dist;
    nearestPt = q1;
  }
  dist = Distance.pointToSegment(q2, p1, p2);
  if (dist < minDist) {
    minDist = dist;
    nearestPt = q2;
  }
  return nearestPt;
}