export function findClosestPointOnLineSegment()

in modules/react-map-gl-draw/src/edit-modes/utils.ts [66:90]


export function findClosestPointOnLineSegment(
  p1: Position,
  p2: Position,
  p: Position
): Position | null {
  // line
  const k = (p2[1] - p1[1]) / (p2[0] - p1[0]);
  const b = p1[1] - k * p1[0];

  // vertical line
  if (!isFinite(k)) {
    const q: Position = [p1[0], p[1]];
    return inBounds(p1, p2, q) ? q : null;
  }

  // p is on line [p1, p2]
  if (p[0] * k + b - p[1] === 0) {
    return inBounds(p1, p2, p) ? p : null;
  }

  const qx = (k * p[1] + p[0] - k * b) / (k * k + 1);
  const qy = k * qx + b;

  return inBounds(p1, p2, [qx, qy]) ? ([qx, qy] as Position) : null;
}