Related Tags

python

# How to calculate distance using the haversine formula

abhilash

### 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:

• $lat_2$ and $lat_1$ are the latitudes of the two points.
• $long_2$ and $long_1$ are the longitudes of the two points.
• $d$ is the distance between the two coordinates.
• $r$ 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 − long2
• R is the radius of the earth, that is, 6,371 kilometers.

### Code


import math

def haversine_distance(coord1: tuple, coord2: tuple):
lon1, lat1 = coord1
lon2, lat2 = coord2

R = 6371000

a = math.sin(delta_phi / 2.0) ** 2 + math.cos(phi_1) * math.cos(phi_2) * math.sin(delta_lambda / 2.0) ** 2

c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))

meters = R * c
km = meters / 1000.0

meters = round(meters, 3)
km = round(km, 3)
miles = km * 0.621371
print(f"Distance: {meters} m")
print(f"Distance: {km} km")
print(f"Distance: {miles} miles")

if __name__ == "__main__":
lat1 = 43.2341
lon1 = 0.5463
lat2 = 58.1234
lon2 = 88.9421

coord1 = (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.

RELATED TAGS

python

CONTRIBUTOR

abhilash
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time