What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleFind the distance between a point and a line segment
DescriptionThis example shows how to find the distance between a point and a line segment in Visual Basic 6. The program calculates the point on the segment closest to thue target point.
Keywordsdistance, point-to-line, line-to-line, point, line
Thanks to Steve Redmond for pointing out a bug in this code.

This example treats the segment as parameterized vector where the parameter t varies from 0 to 1. It finds the value of t that minimizes the distance from the point to the line. If t is between 0.0 and 1.0, then the closest point lies on the segment, otherwise the closest point is one of the segment's end points. The program finds this closest point and calculates the dstance between it and the target point.

' Calculate the distance between the point and the segment.
Private Function DistToSegment(ByVal px As Single, ByVal py _
    As Single, ByVal X1 As Single, ByVal Y1 As Single, _
    ByVal X2 As Single, ByVal Y2 As Single, ByRef near_x As _
    Single, ByRef near_y As Single) As Single
Dim dx As Single
Dim dy As Single
Dim t As Single

    dx = X2 - X1
    dy = Y2 - Y1
    If dx = 0 And dy = 0 Then
        ' It's a point not a line segment.
        dx = px - X1
        dy = py - Y1
        near_x = X1
        near_y = Y1
        DistToSegment = Sqr(dx * dx + dy * dy)
        Exit Function
    End If

    ' Calculate the t that minimizes the distance.
    t = ((px - X1) * dx + (py - Y1) * dy) / (dx * dx + dy * _

    ' See if this represents one of the segment's
    ' end points or a point in the middle.
    If t < 0 Then
        dx = px - X1
        dy = py - Y1
        near_x = X1
        near_y = Y1
    ElseIf t > 1 Then
        dx = px - X2
        dy = py - Y2
        near_x = X2
        near_y = Y2
        near_x = X1 + t * dx
        near_y = Y1 + t * dy
        dx = px - near_x
        dy = py - near_y
    End If

    DistToSegment = Sqr(dx * dx + dy * dy)
End Function
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.