Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA haversine formula

I am trying to implement Haversine formula into excel function. Its looks like this:

Public Function Haversine(Lat1 As Variant, Lon1 As Variant, Lat2 As Variant, Lon2 As Variant)
Dim R As Integer, dlon As Variant, dlat As Variant, Rad1 As Variant
Dim a As Variant, c As Variant, d As Variant, Rad2 As Variant

R = 6371
dlon = Excel.WorksheetFunction.Radians(Lon2 - Lon1)
dlat = Excel.WorksheetFunction.Radians(Lat2 - Lat1)
Rad1 = Excel.WorksheetFunction.Radians(Lat1)
Rad2 = Excel.WorksheetFunction.Radians(Lat2)
a = Sin(dlat / 2) * Sin(dlat / 2) + Cos(Rad1) * Cos(Rad2) * Sin(dlon / 2) * Sin(dlon / 2)
c = 2 * Excel.WorksheetFunction.Atan2(Sqr(a), Sqr(1 - a))
d = R * c
Haversine = d
End Function

But when im testing it I am getting wrong distance... I dont understand why. For coordinates used in this topic : Function to calculate distance between two coordinates shows wrong I am getting 20013,44 as output. Anyone knows what is wrong here? Cant find my mistake...

like image 812
banshe Avatar asked Feb 03 '16 10:02

banshe


People also ask

How do I calculate the distance between two points in Excel?

Here are the formulas for degree coordinates: Cell B5: =distvincenty(B2,C2,B3,C3) Cell D5: =MOD(DEGREES(ATAN2(COS(B2*PI()/180) *SIN(B3*PI()/180)-SIN(B2*PI()/180) *COS(B3*PI()/180) *COS(C3*PI()/180-C2*PI()/180), SIN(C3*PI()/180-C2*PI()/180) *COS(B2*PI()/180)))+360,360)


1 Answers

Atan2 is defined back to front in Excel compared to JavaScript i.e. Atan2(x,y) rather than Atan2(y,x).

You need to reverse the order of the two arguments:-

c = 2 * Excel.WorksheetFunction.Atan2(Sqr(1 - a), Sqr(a))

See this

So

=haversine(59.3293371,13.4877472,59.3225525,13.4619422)

gives

1.65 km

which is the correct distance as the crow flies.

like image 165
Tom Sharpe Avatar answered Sep 28 '22 02:09

Tom Sharpe