Search code examples
mathgeometrylinepoint

Finding nearest line and its x,y location


Suppose that I have the following graph. I know A,B,C,D,E location(x,y). My problem is how to find which line is the nearest with point E. And also I want to draw a new line (blue color) between point and the nearest line. How can I found the (x,y) so that I can draw the line?

enter image description here


Solution

  • You need to make projection of point E onto line AB, determine whether that projection lies in the range of AB segment and find length of perpendicular to projection point. Same for CD segment.

    To find projection point, get direction vector of AB and AE

    AB = (B - A)
    AE = (E - A)
    

    and find parameter using scalar product of

     t = (AB * AE) / (AB * AB) 
    

    if t lies out of rnage 0..1, then the closest point of segment is one of the ends. Otherwise find propjection point and length of projection

    P = A + AB * t
    Len = length(E - P)