Here you can find the source of distancePointToLine(final double x0, final double y0, final double x1, final double y1, final double xp, final double yp)
Parameter | Description |
---|---|
x0 | x coordinate of P0 that defines the line |
y0 | y coordinate of P0 that defines the line |
x1 | x coordinate of P1 that defines the line |
y1 | y coordinate of P1 that defines the line |
xp | x coordinate of point |
yp | y coordinate of point |
public static double distancePointToLine(final double x0, final double y0, final double x1, final double y1, final double xp, final double yp)
//package com.java2s; public class Main { /**/*from w w w .j a va2 s . c om*/ * Compute the distance of a point from a line. Note that the line * is merely defined by the two points and continues to infinity * in both directions. So the projection of the point does * not have to lie within the two points (they are not the end points). * * @param x0 x coordinate of P0 that defines the line * @param y0 y coordinate of P0 that defines the line * @param x1 x coordinate of P1 that defines the line * @param y1 y coordinate of P1 that defines the line * @param xp x coordinate of point * @param yp y coordinate of point * @return distance between the line and the point. */ public static double distancePointToLine(final double x0, final double y0, final double x1, final double y1, final double xp, final double yp) { double[] pt = projectPointOntoLine(x0, y0, x1, y1, xp, yp); return Math.sqrt((pt[0] - xp) * (pt[0] - xp) + (pt[1] - yp) * (pt[1] - yp)); } /** * Find the point on the line that is closest to the specified point. * * Equation of a line: * P = P0 + u(P1 - P0) * * P2 is the point on the line that is closest to P * (P2-P) dot (P2-P1) = 0 * * @param x0 x coordinate of P0 that defines the line * @param y0 y coordinate of P0 that defines the line * @param x1 x coordinate of P1 that defines the line * @param y1 y coordinate of P1 that defines the line * @param xp x coordinate of point * @param yp y coordinate of point * @return an array containing the x,y coordinate of the closest point. */ public static double[] projectPointOntoLine(final double x0, final double y0, final double x1, final double y1, final double xp, final double yp) { double u = (xp - x0) * (x1 - x0) + (yp - y0) * (y1 - y0); u = u / ((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0)); // location of the point on the line where the tangent intersects double x = x0 + u * (x1 - x0); double y = y0 + u * (y1 - y0); return new double[] { x, y }; } }