public Coordinate nearest ( Coordinate c ) { double len = this . getLength ( ) ; double u = ( c . getX ( ) - this . c1 . getX ( ) ) * ( this . c2 . getX ( ) - this . c1 . getX ( ) ) + ( c . getY ( ) - this . c1 . getY ( ) ) * ( this . c2 . getY ( ) - this . c1 . getY ( ) ) ; u = u / ( len * len ) ; if ( u < 0.00001 || u > 1 ) { // Shortest point not within LineSegment, so take closest end-point. LineSegment ls1 = new LineSegment ( c , this . c1 ) ; LineSegment ls2 = new LineSegment ( c , this . c2 ) ; double len1 = ls1 . getLength ( ) ; double len2 = ls2 . getLength ( ) ; if ( len1 < len2 ) { return this . c1 ; } return this . c2 ; } else { // Intersecting point is on the line, use the formula: P = P1 + u (P2 - P1) double x1 = this . c1 . getX ( ) + u * ( this . c2 . getX ( ) - this . c1 . getX ( ) ) ; double y1 = this . c1 . getY ( ) + u * ( this . c2 . getY ( ) - this . c1 . getY ( ) ) ; return new Coordinate ( x1 , y1 ) ; } }
Calculate which point on the LineSegment is nearest to the given coordinate . Will be perpendicular or one of the end - points .