# 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);
}
{"extraction_info": {"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 1, "mathjax_display_tex": 1, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "math_score": 0.7991028428077698, "perplexity": 1146.7695467108497}, "config": {"markdown_headings": true, "markdown_code": true, "boilerplate_config": {"ratio_threshold": 0.3, "absolute_threshold": 10, "end_threshold": 15, "enable": true}, "remove_buttons": true, "remove_image_figures": true, "remove_link_clusters": true, "table_config": {"min_rows": 2, "min_cols": 3, "format": "plain"}, "remove_chinese": true, "remove_edit_buttons": true, "extract_latex": true}, "warc_path": "s3://commoncrawl/crawl-data/CC-MAIN-2022-40/segments/1664030337446.8/warc/CC-MAIN-20221003231906-20221004021906-00343.warc.gz"}