'Calculate the distance between the point and the segment.
'original from http://vb-helper.com/howto_distance_point_to_line.html
Public Sub DistToSegment(myLoc As LatLng, p1 As LatLng, p2 As LatLng) As Double
Dim dx As Double
Dim dy As Double
Dim t As Double
'Dim dm As doManeuver
Dim dist As Double
Dim px , py , X1 , Y1 , X2 , Y2 , near_x , near_y As Double
Dim p_near As String
Dim g As Geodesic
'dm.Initialize
g.Initialize
Dim u As UTM
Dim ll As LatLon
ll.Initialize
ll.lat = myLoc.Latitude
ll.lon = myLoc.Longitude
u = g.WGS84LatLonToUTM(ll)
px=u.X
py=u.Y
ll.Initialize
ll.lat = p1.Latitude
ll.lon = p1.Longitude
u = g.WGS84LatLonToUTM(ll)
X1 = u.X
Y1 = u.Y
ll.Initialize
ll.lat = p2.Latitude
ll.lon = p2.Longitude
u = g.WGS84LatLonToUTM(ll)
X2 = u.X
Y2 = u.Y
dx = X2 - X1
dy = Y2 - Y1
' Log("dx: " & dx)
' Log("dy: " & dy)
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
dist = Sqrt(dx * dx + dy * dy)
p_near = "P1"
Else
' Calculate the t that minimizes the distance.
t = ((px - X1) * dx + (py - Y1) * dy) / (dx * dx + dy * 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
p_near = "P1"
Else If t > 1 Then
dx = px - X2
dy = py - Y2
near_x = X2
near_y = Y2
p_near = "P2"
Else
near_x = X1 + t * dx
near_y = Y1 + t * dy
dx = px - near_x
dy = py - near_y
p_near = "0"
End If
dist = Sqrt(dx * dx + dy * dy)
End If
'Log("Dist " & dist & " Near " & P_near)
Return dist
End Sub