Here you can find the source of nearestPointOnLine(Line2D l, Point2D p, boolean clampToSegment, Point2D dest)
public static Point2D nearestPointOnLine(Line2D l, Point2D p, boolean clampToSegment, Point2D dest)
//package com.java2s; //License from project: Apache License import java.awt.geom.Line2D; import java.awt.geom.Point2D; public class Main { public static Point2D nearestPointOnLine(Line2D l, Point2D p, boolean clampToSegment, Point2D dest) { if (dest == null) { dest = new Point2D.Double(); }/* w ww. ja v a 2 s . c o m*/ 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; } }