Java Distance between Point and Line distanceToLine2(Line2D l, Point2D p)

Here you can find the source of distanceToLine2(Line2D l, Point2D p)

Description

distance To Line

License

Apache License

Declaration

public static double distanceToLine2(Line2D l, Point2D p) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.awt.geom.Line2D;
import java.awt.geom.Point2D;

public class Main {
    public static double distanceToLine2(Line2D l, Point2D p) {

        Point2D p2 = nearestPointOnLine(l, p, true, null);
        return p.distance(p2);
    }//ww  w.j av a2 s . c  o m

    public static Point2D nearestPointOnLine(Line2D l, Point2D p, boolean clampToSegment, Point2D dest) {
        if (dest == null) {
            dest = new Point2D.Double();
        }

        double apx = p.getX() - l.getX1();
        double apy = p.getY() - l.getY1();
        double abx = l.getX2() - l.getX1();
        double aby = l.getY2() - l.getY1();

        double ab2 = abx * abx + aby * aby;
        double ap_ab = apx * abx + apy * aby;
        double t = ap_ab / ab2;
        if (clampToSegment) {
            if (t < 0) {
                t = 0;
            } else if (t > 1) {
                t = 1;
            }
        }
        dest.setLocation(l.getX1() + abx * t, l.getY1() + aby * t);
        return dest;
    }

    public static double distance(Point2D a, Point2D b) {
        return a.distance(b);
    }
}

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. distanceToLine(Point2D p, Point2D endA, Point2D endZ)
  6. distanceToLine3(Line2D l, Point2D p)
  7. getDistance(double aX, double aY, double bX, double bY)
  8. getDistance(Line2D aSegment, Point aPoint)
  9. getDistanceToCenter(Point2D p, Line2D line)