VBA to get Distance in miles, kilometers, or nautical miles from two coordinate points of Latutude and Longitude.
On the left is earth. It is round and has a radius from the center to each point on the surface. The radius of the earth is not the same everywhere, so an approximation is used.
On the right, coordinates for 2 cities are labeled. Unlike standard math where a coordinate number pair has the distance along the X-Axis (horizontal) first and second is the distance along the Y-axis, geological coordinates are usually reported with Latitude first, and then Longitude. Coordinates are in degrees with +/-90° being the extremity for Latitude, and +/- 180° for Longitude.
To convert degrees to radians, divide by 180/pi, which is 57.2958 (since there are pi radians in a half circle, which is 180°).
Sin (sine) of an angle is is opposite/hypotenuse.
Cos (cosine) of an angle is adjacent/hypotenuse.
Atn (arc tangent) = the inverse of tangent (opposite/adjacent); the arc tan is the angle in radians for a given tangent.
A circle has 2(pi) radians (360°). The distance all around it is the circumference, which is 2(pi)R ... or (pi)D -- remember that from school? Therefore: the length of an arc is the angle in radians times the radius.
'*************** Code Start ***************************************************** ' Purpose : Get distance between 2 points of Latitude and Longitude ' Author : crystal (strive4peace) ' Return : Double ' License : below code ' Code List: www.MsAccessGurus.com/code.htm '-------------------------------------------------------------------------------' GetDistance
'------------------------------------------------------------------------------- ' Public Function GetDistance( _ pLat1 As Double _ , pLng1 As Double _ , pLat2 As Double _ , pLng2 As Double _ , Optional pWhich As Integer _ ) As Double 'strive4peace 12-13-08, 12-22 On Error Resume Next Dim X As Double Dim EarthRadius As Double Select Case pWhich Case 2: EarthRadius = 6378.7 'kilometers Case 3: EarthRadius = 3437.74677 'nautical miles Case Else EarthRadius = 3963 'statute miles End Select X = (Sin(pLat1 / 57.2958) * Sin(pLat2 / 57.2958)) _ + (Cos(pLat1 / 57.2958) * Cos(pLat2 / 57.2958) * Cos(pLng2 / 57.2958 - pLng1 / 57.2958)) GetDistance = ABS ( EarthRadius * Atn(Sqr(1 - X ^ 2) / X) ) End Function ' ' LICENSE ' You may freely use and share this code ' provided this license notice and comment lines are not changed; ' code may be modified provided you clearly note your changes. ' You may not sell this code alone, or as part of a collection, ' without my handwritten permission. ' All ownership rights reserved. Use at your own risk. ' ~ crystal (strive4peace) www.MsAccessGurus.com '*************** Code End *******************************************************