Java Distance Calculate distanceFromLineToPoint(double x1, double y1, double z1, double x2, double y2, double z2, double px, double py, double pz)

Here you can find the source of distanceFromLineToPoint(double x1, double y1, double z1, double x2, double y2, double z2, double px, double py, double pz)

Description

Get the shortest distance from a line segment to a point

License

Open Source License

Parameter

Parameter Description
x1 a parameter
y1 a parameter
z1 a parameter
x2 a parameter
y2 a parameter
z3 a parameter
px a parameter
py a parameter
pz a parameter

Return

the distance, which will be >= 0.0; or -1.0, if the point is beyond the segment's ends

Declaration

public static double distanceFromLineToPoint(double x1, double y1, double z1, double x2, double y2, double z2,
        double px, double py, double pz) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from   ww  w . ja  v  a2  s . c  o m
     * Get the shortest distance from a line segment to a point
     * @param x1
     * @param y1
     * @param z1
     * @param x2
     * @param y2
     * @param z3
     * @param px
     * @param py
     * @param pz
     * @return the distance, which will be >= 0.0; or -1.0, if the point is beyond the segment's ends
     */
    public static double distanceFromLineToPoint(double x1, double y1, double z1, double x2, double y2, double z2,
            double px, double py, double pz) {
        double ddx = x2 - x1;
        double ddy = y2 - y1;
        double ddz = z2 - z1;
        double lineMag = ddx * ddx + ddy * ddy + ddz * ddz;

        double u = (((px - x1) * ddx) + ((py - y1) * ddy) + ((pz - z1) * ddz)) / lineMag;

        if (u < 0.0f || u > 1.0f) {
            return -1.0; // closest point does not fall within the line segment
        }

        double ix = x1 + u * (x2 - x1);
        double iy = y1 + u * (y2 - y1);
        double iz = z1 + u * (z2 - z1);

        ddx = ix - px;
        ddy = iy - py;
        ddz = iz - pz;
        return Math.sqrt(ddx * ddx + ddy * ddy + ddz * ddz);
    }

    public static double distanceFromLineToPoint(double x1, double y1, double x2, double y2, double px, double py) {
        return distanceFromLineToPoint(x1, y1, 0.0, x2, y2, 0.0, px, py, 0.0);
    }
}

Related

  1. distanceCorrelation(final double[][] x, final double[][] y)
  2. distanceDamerauLevenshtein(CharSequence source, CharSequence target)
  3. distanceFast(double lat1, double lon1, double lat2, double lon2)
  4. distanceFrom(double lat1, double long1, double lat2, double long2)
  5. DistanceFromLine(float cx, float cy, float ax, float ay, float bx, float by)
  6. distanceFromZero(int x, int y)
  7. distanceHaversine(Double lat1, Double lon1, Double lat2, Double lon2, String param)
  8. distanceInf(double[] p1, double[] p2)
  9. distanceInMeters(double lat1, double lon1, double lat2, double lon2)