Snippet: Distance between a line and a point

Given a line segment between two points \(\mathbf{A}\) and \(\mathbf{B}\), we want to know the smallest distance between the point \(\mathbf{P}\) and the line segment. To do so, we only need to find the normal \(\mathbf{n}\) to the line segment, which basically is the perpendicular vector of \(\mathbf{v}\):

\[\mathbf{n} = \mathbf{v}^\perp\]

Now the distance \(d\) between the line and point \(\mathbf{P}\) is thus the vector projection of \(\mathbf{m} = \mathbf{P} - \mathbf{A}\) onto \(\mathbf{n}\), which is

\[d = \frac{|\mathbf{n}\cdot\mathbf{m}|}{|\mathbf{n}|} = |\hat{\mathbf{v}}^\perp\cdot\mathbf{m}|\]

JavaScript Implementation

function linePointDistance(A, B, P) {

  var n = {x: A.y - B.y, y: B.x - A.x};
  var m = {x: P.x - A.x, y: P.y - A.y};
  return Math.abs(n.x * m.x + n.y * m.y) / Math.sqrt(n.x * n.x + n.y * n.y);