In connection with an analysis on the geographical spread of workshops and car customers, I needed a way to calculate the distance (kilometers) between two sets of coordinates (latitude/longitude format).
From my time in the Navy, I remembered using the Haversine Formula to calculate what is called great-circle distances from one position to another. The formula gives you the bee-line distance between the two positions in either Km or miles.
The code is adopted from here and changed from miles to kilometers.
Read about the Haversine formula here.
And here’s a page where you can get lat/long coodinates to play around with.
Since it is a function, remember to insert it in a module.
Here is the code (Returns distance in Km):
Function GetKM(lat1Degrees As Double, lon1Degrees As Double, lat2Degrees As Double, lon2Degrees As Double) Dim earthSphereRadiusKilometers As Double Dim kilometerConversionToMilesFactor As Double Dim lat1Radians As Double Dim lon1Radians As Double Dim lat2Radians As Double Dim lon2Radians As Double Dim AsinBase As Double Dim DerivedAsin As Double 'Mean radius of the earth (replace with 3443.89849 to get nautical miles) earthSphereRadiusKilometers = 6371 'Convert kilometers into miles kilometerConversionToMilesFactor = 0.621371 'Convert each decimal degree to radians lat1Radians = (lat1Degrees / 180) * 3.14159265359 lon1Radians = (lon1Degrees / 180) * 3.14159265359 lat2Radians = (lat2Degrees / 180) * 3.14159265359 lon2Radians = (lon2Degrees / 180) * 3.14159265359 AsinBase = Sin(Sqr(Sin((lat1Radians - lat2Radians) / 2) ^ 2 + Cos(lat1Radians) * Cos(lat2Radians) * Sin((lon1Radians - lon2Radians) / 2) ^ 2)) DerivedAsin = (AsinBase / Sqr(-AsinBase * AsinBase + 1)) 'Get distance from [lat1,lon1] to [lat2,lon2] GetKM = Round(2 * DerivedAsin * earthSphereRadiusKilometers, 2) 'Miles: = Round(2 * DerivedAsin * (earthSphereRadiusKilometers * kilometerConversionToMilesFactor), 2) End Function