How to calculate distance using the haversine formula
Overview
The haversine formula calculates the shortest distance between two points, whose latitudes and longitudes are known, in a sphere. When used for points on the Earth, the calculated distance is approximate as the formula assumes the Earth to be a perfect sphere.
The haversine formula can be expressed as follows:
The central angle haversine can be computed as follows:
The values in the formula above stand for the following:
- and are the latitudes of the two points.
- and are the longitudes of the two points.
- is the distance between the two coordinates.
- is the radius of the earth, that is, 6,371 kilometers.
We can derive the haversine formula to calculate the distance d between two points as follows:
a = sin²(Δlat/2) + cos(lat1).cos(lt2).sin²(Δlong/2)
c = 2.atan2(√a, √(1−a))
d = R.c
In the formula above, the values are calculated as follows:
Δlat = lat1 − lat2Δlong = long1 − long2Ris the radius of the earth, that is, 6,371 kilometers.
Code
import mathdef haversine_distance(coord1: tuple, coord2: tuple):lon1, lat1 = coord1lon2, lat2 = coord2R = 6371000phi_1 = math.radians(lat1)phi_2 = math.radians(lat2)delta_phi = math.radians(lat2 - lat1)delta_lambda = math.radians(lon2 - lon1)a = math.sin(delta_phi / 2.0) ** 2 + math.cos(phi_1) * math.cos(phi_2) * math.sin(delta_lambda / 2.0) ** 2c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))meters = R * ckm = meters / 1000.0meters = round(meters, 3)km = round(km, 3)miles = km * 0.621371print(f"Distance: {meters} m")print(f"Distance: {km} km")print(f"Distance: {miles} miles")if __name__ == "__main__":lat1 = 43.2341lon1 = 0.5463lat2 = 58.1234lon2 = 88.9421coord1 = (lat1, lon1)coord2 = (lat2, lon2)print("Distance between", coord1, "and" , coord2, ":")haversine_distance(coord1, coord2)
Explanation
- Line 8: We define the radius of the earth.
- Lines 9-10: The latitude values are converted to radians.
- Line 12: The difference between the latitudes is calculated.
- Line 13: The difference between the longitudes is calculated.
- Lines 15, 17, 19: The formula in the overview section is implemented to get the distance in meters.
- Line 20: The distance is calculated in kilometers.
- Line 22, 23: The distances are rounded to 3 decimal points.
- Line 24: The distance is calculated in miles.
- Lines 25-27: The distance in different units is printed.
- Lines 31-37: The coordinates are defined.
- Line 39:
haversine_distance()method is invoked to find the haversine distance.