Here you can find the source of nearestColinearPoint(final Line2D segment, final Point2D point)
public static Point2D nearestColinearPoint(final Line2D segment, final Point2D point)
//package com.java2s; /*//from w w w . jav a 2s . c o m * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2001-2008, Open Source Geospatial Foundation (OSGeo) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ import java.awt.geom.Line2D; import java.awt.geom.Point2D; public class Main { public static Point2D nearestColinearPoint(final Line2D segment, final Point2D point) { return nearestColinearPoint(segment.getX1(), segment.getY1(), segment.getX2(), segment.getY2(), point.getX(), point.getY()); } public static Point2D nearestColinearPoint(final double x1, final double y1, final double x2, final double y2, double x, double y) { final double slope = (y2 - y1) / (x2 - x1); if (!Double.isInfinite(slope)) { final double y0 = (y2 - slope * x2); x = ((y - y0) * slope + x) / (slope * slope + 1); y = x * slope + y0; } else { x = x2; } if (x1 <= x2) { if (x < x1) x = x1; if (x > x2) x = x2; } else { if (x > x1) x = x1; if (x < x2) x = x2; } if (y1 <= y2) { if (y < y1) y = y1; if (y > y2) y = y2; } else { if (y > y1) y = y1; if (y < y2) y = y2; } return new Point2D.Double(x, y); } }