Hi Rick,
I'm working to create a function that returns the midpoint of a line segment using longitude latitude. I found numerous sources that discuss the logic and even one website that gives the code in javascript. (Calculate distance and bearing between two Latitude/Longitude points using Haversine formula in JavaScript - under "Midpoint")
I believe the initial calculations were listed here, I also used his example to test my code: Math Forum - Ask Dr. Math
My code that is returning the incorrect answer:
Code:
Sub GCMdPnt()
'http://www.movable-type.co.uk/scripts/latlong.html
Dim Lat1 As Double, Lat2 As Double, Lng1 As Double, Lng2 As Double
Dim dBx As Double, dBy As Double, Lat3 As Double, Lng3 As Double
Lat1 = 34.22222222
Lng1 = 118.4111111
Lat2 = 40.66972222
Lng2 = 73.94388889
dBx = Cos(Lat2) * Cos(Lng2 - Lng1)
dBy = Cos(Lat2) * Sin(Lng2 - Lng1)
Lat3 = ATAN_2(Sin(Lat1) + Sin(Lat2), _
Sqr((Cos(Lat1) + dBx) ^ 2 + dBy ^ 2))
Lng3 = Lng1 + ATAN_2(dBy, Cos(Lat1) + dBx)
Debug.Print Lat3 & "_" & Lng3
'Should equal 39.54707861_97.201534
End Sub
Function ATAN_2(X As Double, Y As Double)
Const C_PI As Double = 3.14159265359
Select Case Sgn(X)
Case -1
ATAN_2 = Atn(Y / X) + (C_PI * Sgn(Y))
Case 0
If Sgn(Y) Then
ATAN_2 = Sgn(Y) * C_PI / 2
Else
Err.Raise 11
End If
Case 1
ATAN_2 = Atn(Y / X)
End Select
End Function
If the ArcTangent function does not seem correct, worksheetfunction.atan2(x,y) can also be used. Any idea why I'm returning: 1.31_117.09 ? Thank you in advance.
Bookmarks