Calculate Geographic distances in Python with the Haversine method

Johan Louwers
3 min readSep 18
Oslo — Amersfoort

When calculating distance between points on earth you will have to use the Haversine method for this.

Haversine method explained

The Haversine method is a mathematical formula used in navigation and geography to calculate the distance between two points on the surface of a sphere, such as the Earth. It’s particularly useful for determining distances over short to medium distances on the Earth’s surface.

The formula is based on the law of haversines, which relates the sides and angles of spherical triangles. In the context of the Haversine formula, it’s used to find the great-circle distance between two points, which is the shortest distance over the Earth’s surface.

Haversine formula

- d is the distance between the two points (along the surface of the sphere).
- R is the radius of the sphere (in this case, the radius of the Earth).
- lat1​ and lat2​ are the latitudes of the two points.
- Δlat is the difference between the latitudes.
- Δlon is the difference between the longitudes.
- atan2 is a special function that computes the arctangent of the quotient of its arguments.

The result, d, will be in the same units as the radius of the sphere (e.g., kilometers if the radius of the Earth is used).

Keep in mind that the Haversine formula assumes a perfect sphere, which is an approximation of the Earth’s shape. For more accurate results, especially over long distances, other ellipsoidal models like the Vincenty formulae or more complex geodetic models might be used.

Calculate in Python

When you want to calculate this using python you can use the below example. In this example we have taken a location in the Netherands (Amersfoort) and a location in Norway (Oslo).

import math

def haversine(lat1, lon1, lat2, lon2):
# Convert latitude and longitude from degrees to radians
lat1 = math.radians(lat1)…
Johan Louwers

Johan Louwers is a technology enthousiasts with a long background in supporting enterprises and startups alike as CTO, Chief Enterprise Architect and developer.