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
![](/images/calculate_distance/h_formula.png)
1 | import math |
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 | from geopy.distance import geodesic |
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 | from haversine import haversine, Unit |
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.