Haversine formula – Calculate distance between two Latitude/Longitude


Haversine formula is a very popular and often used method at developing GPS applications. The Haversine formula is used to calculate
distance by latitude and longitude of two different points. This is the shortest distance between two points on the Earth’s surface.

Mathematical foundation

Φ – latitude, λ – longitude, R – radius of the earth (R ≈ 6.371 km)

Implementing a pattern on a database query using SQL looks like
as follows:

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) )
* cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin(radians(lat)) ) ) AS distance
FROM issues
ORDER BY distance;

A big plus of use Haversine formula is that it can be implemented in SQL, and thus the time-consuming calculations of the distance are transferred from the application to the database.