Public Function CalculateBearing(ByVal Lat1 As Double, ByVal Lon1 As Double, ByVal Lat2 As Double, ByVal Lon2 As Double) As String
Dim dLat1 As Double
Dim dLon1 As Double
Dim dLat2 As Double
Dim dLon2 As Double
Dim dBearing As Double
dLat1 = Deg2Rad(Lat1)
dLon1 = Deg2Rad(Lon1)
dLat2 = Deg2Rad(Lat2)
dLon2 = Deg2Rad(Lon2)
' The bearing should be "IDLE" if the bus doesn't move
If Map.Distance(Lon1, Lat1, Lon2, Lat2) < 0.02 Then
CalculateBearing = Bearing
End If
dBearing = GetBearing(dLat1, dLon1, dLat2, dLon2)
CalculateBearing = GetDirectionBearingFromDegrees(Rad2Deg(dBearing))
End Function
Private Function Deg2Rad(ByVal Deg As Double) As Double
Deg2Rad = Deg * PI / 180
End Function
Private Function Rad2Deg(ByVal Rad As Double) As Double
Rad2Deg = Rad * 180 / PI
End Function
Private Function GetDirectionBearingFromDegrees(ByVal Deg As Double) As String
If Deg < -157.5 Then
GetDirectionBearingFromDegrees = "S"
Exit Function
End If
If Deg < -112.5 Then
GetDirectionBearingFromDegrees = "SW"
Exit Function
End If
If Deg < -67.5 Then
GetDirectionBearingFromDegrees = "W"
Exit Function
End If
If Deg < -22.5 Then
GetDirectionBearingFromDegrees = "NW"
Exit Function
End If
If Deg < 22.5 Then
GetDirectionBearingFromDegrees = "N"
Exit Function
End If
If Deg < 67.5 Then
GetDirectionBearingFromDegrees = "NE"
Exit Function
End If
If Deg < 112.5 Then
GetDirectionBearingFromDegrees = "E"
Exit Function
End If
If Deg < 157.5 Then
GetDirectionBearingFromDegrees = "SE"
Exit Function
End If
GetDirectionBearingFromDegrees = "S"
End Function
Private Function GetBearing(ByVal p1Lat As Double, ByVal p1Lon As Double, ByVal p2Lat As Double, ByVal p2Lon As Double) As Double
Dim x As Double
Dim y As Double
y = Math.Sin(p1Lon - p2Lon) * Math.Cos(p2Lat)
x = Math.Cos(p1Lat) * Math.Sin(p2Lat) - Math.Sin(p1Lat) * Math.Cos(p2Lat) * Math.Cos(p1Lon - p2Lon)
GetBearing = Atan2(-y, x)
End Function
Private Function Atan2(ByVal y As Double, ByVal x As Double) As Double
If x > 0 Then
Atan2 = Atn(y / x)
ElseIf x < 0 Then
Atan2 = Atn(y / x) + PI
Else
Atan2 = PI / 2 * Sgn(y)
End If
End Function