Calculate Distance Between Two Points Given Latitude and Longitude in Python

How to calculate the distance between two coordinate points (knowing longitude and latitude) in Python? Three methods are given here:

Implement the Haversine formula

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import math
from math import radians, sin, cos, asin

def haversine(lat1, lon1, lat2, lon2):
# The average radius of the earth is approximately 6371.393km
EARTH_RADIUS = 6371

# Convert to radians
lat1 = radians(lat1)
lon1 = radians(lon1)
lat2 = radians(lat2)
lon2 = radians(lon2)

# Calculate the difference between converted latitude and longitude
delta_lat = lat2 - lat1
delta_lon = lon2 - lon1

# Haversine formula
temp = math.pow(sin(delta_lat / 2), 2) + cos(lat1) * cos(lat2) * math.pow(sin(delta_lon / 2), 2)
distance = 2 * asin(math.sqrt(temp)) * EARTH_RADIUS

return distance

new_dist = haversine(36.1628, 114.2581, 36.5935, 114.6296)
print("The distance calculated using the Haversine formula is:", new_dist, "km")

The output is as follows:

1
The distance calculated using the Haversine formula is: 58.30722422948836 km

GeoPy

GeoPy is a Python library about geocoding. It has geocoding, latitude and longitude distance calculation and other functions. Use pip install geopy to install it.

GeoPy’s documentation: https://geopy.readthedocs.io/en/stable/.

1
2
3
4
from geopy.distance import geodesic

distance = geodesic((36.1628, 114.2581), (36.5935, 114.6296)).km
print("The distance calculated using GeoPy is:", distance, "km")

The output is as follows:

1
The distance calculated using GeoPy is: 58.27002330025926 km

haversine library

Use pip install haversine to install the haversine library in Python.

1
2
3
4
5
6
7
from haversine import haversine, Unit

point1 = (36.1628, 114.2581)
point2 = (36.5935, 114.6296)

distance = haversine(point1, point2, unit=Unit.KILOMETERS) # km
print("The distance calculated using haversine library is:", distance, "km")

The output is as follows:

1
The distance calculated using haversine library is: 58.307304766856625 km

It can be seen that for the given two longitude and latitude coordinates, the results calculated by different methods still have certain errors.