I'm trying to convert the Haversine formula from VB.NET to VBA but am running into some problems. Does anyone have this converted already?
Imports System.Text
Public Class CDistanceBetweenLocations
Public Shared Function Calc(ByVal Lat1 As Double, ByVal Long1 As Double, ByVal Lat2 As Double, ByVal Long2 As Double) As Double
'
' The Haversine formula according to Dr. Math.
'
http://mathforum.org/library/drmath/view/51879.html '
' dlon = lon2 - lon1
' dlat = lat2 - lat1
' a = (sin(dlat/2))^2 + cos(lat1) * cos(lat2) * (sin(dlon/2))^2
' c = 2 * atan2(sqrt(a), sqrt(1-a))
' d = R * c
'
' Where
' * dlon is the change in longitude
' * dlat is the change in latitude
' * c is the great circle distance in Radians.
' * R is the radius of a spherical Earth.
' * The locations of the two points in
' spherical coordinates (longitude and
' latitude) are lon1,lat1 and lon2, lat2.
'
Dim dDistance As Double = [Double].MinValue
Dim dLat1InRad As Double = Lat1 * (Math.PI / 180)
Dim dLong1InRad As Double = Long1 * (Math.PI / 180)
Dim dLat2InRad As Double = Lat2 * (Math.PI / 180)
Dim dLong2InRad As Double = Long2 * (Math.PI / 180)
Dim dLongitude As Double = dLong2InRad - dLong1InRad
Dim dLatitude As Double = dLat2InRad - dLat1InRad
' Intermediate result a.
Dim a As Double = Math.Pow(Math.Sin(dLatitud
e / 2), 2) + Math.Cos(dLat1InRad) * Math.Cos(dLat2InRad) * Math.Pow(Math.Sin(dLongitu
de / 2), 2)
' Intermediate result c (great circle distance in Radians).
Dim c As Double = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a))
' Distance.
' R (Earth Radius) mi = 3956.0, nm = 3437.7, 6367.0 = km, 6962560 = Yards, 20887680 = Feet ' comment
'Const kEarthRadiusKms As Double = 6376.5
Const kEarthRadiusKms As Double = 6962560
dDistance = kEarthRadiusKms * c
Return dDistance
End Function
End Class
Start Free Trial