This is a function that I use to calculate distance from the latitude and longitude of two different locations. The earth radius is in Kilometer, and I have tried using both the "average" earth radius, and the calculated earth radius at the starting point. Either way, the answer should be in dozens of Kilometer but the results are over 8,000 and I cannot figure out why.
Anyone that might be able to help me figure out why the result is incorrect?
Public Function CalculateDistance(lat1 As Double, lon1 As Double, lat2 As Double, lon2 As Double) As Double
Function to calculate the straight-line distance between two locations
Const EarthRadius As Double = 6387.59 '6371 is average Radius of the Earth in kilometers
If lon1 < 0 Then lon1 = 360 + lon1
If lon2 < 0 Then lon2 = 360 + lon2
' Convert degrees to radians
lat1 = lat1 * (3.14159265358979 / 180)
lon1 = lon1 * (3.14159265358979 / 180)
lat2 = lat2 * (3.14159265358979 / 180)
lon2 = lon2 * (3.14159265358979 / 180)
' Calculate differences in coordinates
Dim dLat As Double
Dim dLon As Double
dLat = lat2 - lat1
dLon = lon2 - lon1
' Haversine formula to calculate distance
Dim a As Double
Dim c As Double
a = Sin(dLat / 2) ^ 2 + Cos(lat1) * Cos(lat2) * Sin(dLon / 2) ^ 2
c = 2 * Atn2(Sqr(a), Sqr(1 - a))
CalculateDistance = EarthRadius * c
End Function
I was expecting 17.37 kilometers (give or take) and the result was over 8,600 kilometers.