EDIT: For anyone suffering the same problem, I found my own solution. Excel's ATAN2 function uses ATAN2(x,y) while VB uses Math.Atan2(y,x). As soon as I switched those around in my VB code it worked like a charm.
I am computing the distance and bearing between two geographic coordinates. The forumula in excel produces the correct distance (km) and bearing.
This is the formula in the bearing cell
=ATAN2(COS(lat1)*SIN(lat2)-SIN(lat1)*COS(lat2)*COS(lon2-lon1),SIN(lon2-lon1)*COS(lat2))
This is my VB code attempting to do the same thing:
Ive double and triple checked the formula and to my eyes it looks identical to the excel formula. I even put the same coordinates into excel and got the correct answer. Im stumped! Please help!Code:Private Sub dstbrng(ByVal Lat1 As Single, ByVal Lon1 As Single, ByVal Lat2 As Single, ByVal Lon2 As Single) Dim Lat1rad As Double Dim Lon1rad As Double Dim Lat2rad As Double Dim Lon2rad As Double Dim distrad As Double Dim distkm As Double Dim brngrad As Double Dim brngdeg As Double Dim ER As Single ER = 6371 ' Converting coordinates (degrees) to coordinates (radians) through another function I built, works great Lat1rad = Deg2Rad(Lat1) Lat2rad = Deg2Rad(Lat2) Lon1rad = Deg2Rad(Lon1) Lon2rad = Deg2Rad(Lon2) ' This part works great distrad = Math.Acos(Math.Sin(Lat1rad) * Math.Sin(Lat2rad) + Math.Cos(Lat1rad) * Math.Cos(Lat2rad) * Math.Cos(Lon2rad - Lon1rad)) distkm = distrad * ER dbdistm = distkm * 1000 ' This part doesnt brngrad = Math.Atan2(Math.Cos(Lat1rad) * Math.Sin(Lat2rad) - Math.Sin(Lat1rad) * Math.Cos(Lat2rad) * Math.Cos(Lon2rad - Lon1rad), Math.Sin(Lon2rad - Lon1rad) * Math.Cos(Lat2rad)) brngdeg = Rad2Deg(brngrad) dbbrng = brngdeg End Sub




Reply With Quote