Calculate the distance between two sets of co-ordinates 🌍️ 

Charlie ChambersCharlie Chambers Administrator
edited February 16 in Functions Library

Summary

Returns the approximate distance in kilometres between a pair of geographical co-ordinates. Input latitude1, longitude1, latitude2, longitude2, output value is distance between each set of co-ordinates while considering the spherical nature of earth using the law of haversines.


Example

Buckingham Palace, London is located at co-ordinates 51.5014° N (latitude), 0.1419° W (longitude)

The Empire State Building, New York is located at co-ordinates 40.7484° N, 73.9857° W.

Output: 5562.2 (the approximate distance in kilometres between the two given co-ordinates)*





Function walk-through

Converts each supplied co-ordinate into radians as a prerequisite for the Haversine Function.

Creates a new variable ‘PI / 180’ which holds the value of π/180, then each input is multiplied by ‘PI / 180’ to create 4 new variables, lat1, lon1, lat2, lon2 which now hold the co-ordinate values in radians.



Next, we calculate the ΔlatDifference (lat1 – lat2) and ΔlonDifference = (lon1 – lon2) and store these values in new variables dlat and dlon respectively.



Now we perform the first part of the Haversine Function, which can be mathematically expressed as:

sin(dlat/2)² + cos(lat1).cos(lat2).sin(dlon/2)²

We perform these calculations and store the output in a new variable a.



Next we calculate 2.arcsin(√a) and store this output in variable c.



Finally, we multiply variable c by the radius of earth and round to 2 decimal places, to give us the distance between the given co-ordiantes in kilometres. The radius of the earth is approximated at 6367km* in this function. Note that this value can be changed to 3956 to return the distance in miles rather than kilometres.



* N.B. The earth is not a perfect sphere, but is oblate at its poles, due to its rotation. Therefore, the radius of Earth is not constant, though is assumed as 6367km in this formula which may result in minor inaccuracies over long distance calculations, especially where there is a large difference in latitudes present. For precision accuracy this can be calculated at each pair of co-ordinates and averaged, using the below formula:

radius R, radius at equator r1, radius at pole r2

B = (latitude1 + latitude2) / 2

R = √ [ (r1² * cos(B))² + (r2² * sin(B))² ] / [ (r1 * cos(B))² + (r2 * sin(B))² ]

Compatibility

This function was developed in v. 2.6.0.2

Comments

Sign In or Register to comment.