Java Distance between Point and Line distanceToLine(Point2D p, Point2D endA, Point2D endZ)

Here you can find the source of distanceToLine(Point2D p, Point2D endA, Point2D endZ)

Description

Computes distance from a point on a plane to line given by two points.

License

Open Source License

Parameter

Parameter Description
p point, distance from which is to be calculated
endA one end of the line
endZ the other end of the line

Return

distance from p to line, formed by endA and endZ

Declaration

public static double distanceToLine(Point2D p, Point2D endA, Point2D endZ) 

Method Source Code

//package com.java2s;

import java.awt.geom.Point2D;

public class Main {
    /**/*  w w  w.j a  v  a 2s . c  o  m*/
     * Computes distance from a point on a plane to line given by two points.
     * 
     * @param p point, distance from which is to be calculated
     * @param endA one end of the line
     * @param endZ the other end of the line
     * @return distance from p to line, formed by endA and endZ
     */
    public static double distanceToLine(Point2D p, Point2D endA, Point2D endZ) {
        /* Geometry here is:
         * - A and B are points on ends of the line
         * - C is a point, distance from which to AB is to be calculated
         * - D is a point on AB, such that CD is perpendicular to AB.
         * We need to find length of CD. Composing a system of equations:
         * - AC squared = AD squared + CD squared (ACD is a right triangle)
         * - BC squared = BD squared + CD squared (BCD is also a right triangle)
         * - AD + BD = AB (D is on AB)
         * it's solution is obvious from the code :-)
        */
        double AC = p.distance(endA);
        double BC = p.distance(endZ);
        double AB = endA.distance(endZ);
        if (AB == (AC + BC)) {
            return 0;
        }
        double ACs = AC * AC;
        double BCs = BC * BC;
        double AD_BD = (ACs - BCs) / AB;
        double AD = (AD_BD + AB) / 2;
        double CDs = ACs - (AD * AD);
        return Math.sqrt(CDs);
    }
}

Related

  1. distanceFromLine(int xa, int ya, int xb, int yb, int xc, int yc)
  2. distancePointToBot(Point2D.Double sourceLocation, Point2D.Double botLocation)
  3. distancePointToLine(final Point2D point, final Line2D line)
  4. DistanceToLine(double x, double y, double x1, double y1, double x2, double y2)
  5. distanceToLine2(Line2D l, Point2D p)
  6. distanceToLine3(Line2D l, Point2D p)
  7. getDistance(double aX, double aY, double bX, double bY)
  8. getDistance(Line2D aSegment, Point aPoint)