Map Distances and the Haversine Formula
GPS gives positions as latitude and longitude: angles on a sphere, not and on a flat sheet. Treating them as flat coordinates works for a city block and fails badly for a flight. This lesson derives the distances a programmer actually uses: the haversine formula for the great-circle distance, a fast flat approximation and its error, and the compass bearing from one point to another.
Latitude and longitude are angles
A point on Earth is given by its latitude (north–south, −90° to 90°) and longitude (east–west, −180° to 180°). Model Earth as a sphere of radius . Then:
- One degree of latitude is always .
- One degree of longitude shrinks toward the poles: the circle of latitude has radius , so a degree of longitude is . At 60° north it is only half as long as at the equator.
That is exactly what a naive "Pythagoras on the degrees" calculation forgets.
The haversine formula
The shortest path between two points on a sphere runs along a great circle (a circle whose centre is Earth's centre). Its length is times the central angle between the points. The haversine formula computes that angle in a way that stays accurate even for points very close together:
It comes from the spherical law of cosines, rewritten with so that small angles do not lose their digits to (compare the law of cosines in the plane). The name is old: "haversine" is half of the versine, , used in navigation tables.
Flat approximations
For short distances, unroll a small patch of the sphere into a plane. The equirectangular approximation scales the longitude difference by the cosine of the mean latitude, then uses Pythagoras:
It is cheap (one , one sqrt) and within a fraction of a percent for distances of a few hundred kilometres. The naive version without the cosine is wrong everywhere except along the equator.
import math
R = 6371.0
cities = {"Hanoi": (21.0285, 105.8542), "Ho Chi Minh City": (10.8231, 106.6297),
"London": (51.5074, -0.1278), "Paris": (48.8566, 2.3522),
"Oslo": (59.9139, 10.7522), "Helsinki": (60.1699, 24.9384),
"New York": (40.7128, -74.0060), "Tokyo": (35.6762, 139.6503)}
def haversine(p, q):
f1, l1, f2, l2 = map(math.radians, (*p, *q))
a = math.sin((f2 - f1) / 2)**2 + math.cos(f1) * math.cos(f2) * math.sin((l2 - l1) / 2)**2
return 2 * R * math.asin(math.sqrt(a))
def dlon(p, q): # longitude difference wrapped into [-180, 180)
return (q[1] - p[1] + 180) % 360 - 180
def equirect(p, q):
f1, f2 = math.radians(p[0]), math.radians(q[0])
x = math.radians(dlon(p, q)) * math.cos((f1 + f2) / 2)
return R * math.hypot(x, f2 - f1)
def naive(p, q):
return R * math.radians(math.hypot(q[0] - p[0], dlon(p, q)))
pairs = [("Hanoi", "Ho Chi Minh City"), ("London", "Paris"), ("Oslo", "Helsinki"), ("New York", "Tokyo")]
print(f"{'route':28}{'haversine':>10}{'equirect':>10}{'naive':>10}")
for a, b in pairs:
h, e, n = (f(cities[a], cities[b]) for f in (haversine, equirect, naive))
print(f"{a + ' - ' + b:28}{h:10.1f}{e:10.1f}{n:10.1f}")route haversine equirect naive
Hanoi - Ho Chi Minh City 1137.8 1137.8 1138.1
London - Paris 343.6 343.6 403.6
Oslo - Helsinki 786.7 788.2 1577.7
New York - Tokyo 10851.7 12801.2 16282.3
The naive method is close for Hanoi–Ho Chi Minh City, which runs almost due north–south (latitude degrees are the same size everywhere). Oslo–Helsinki runs east–west at 60° north, where longitude degrees are half size, and the naive distance is almost double. For New York–Tokyo even the equirectangular formula is far off: over that distance the sphere cannot be flattened.
Warning: Longitude jumps from 180° to −180° at the antimeridian in the Pacific. New York (−74°) to Tokyo (139.7°) is a difference of 213.7° one way, but only 146.3° the other way. The flat formulas need the difference wrapped into , which is what
dlondoes; haversine does not, because is the same either way.
Note: Earth is slightly flattened (an ellipsoid), so the haversine formula can be off by up to about 0.5%. Surveying and aviation software uses ellipsoid formulas (Vincenty, Karney); for ride sharing, games and "stores near you" the sphere is plenty.
Bearings
The initial bearing is the compass direction you start out in (, ), measured clockwise:
On a great circle the bearing changes along the way (except along meridians and the equator), which is why flight paths look curved on flat maps.
import math
def bearing(p, q):
f1, l1, f2, l2 = map(math.radians, (*p, *q))
y = math.sin(l2 - l1) * math.cos(f2)
x = math.cos(f1) * math.sin(f2) - math.sin(f1) * math.cos(f2) * math.cos(l2 - l1)
return (math.degrees(math.atan2(y, x)) + 360) % 360
def compass(deg):
names = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]
return names[round(deg / 45) % 8]
routes = {"Hanoi -> Ho Chi Minh City": ((21.0285, 105.8542), (10.8231, 106.6297)),
"London -> Paris": ((51.5074, -0.1278), (48.8566, 2.3522)),
"New York -> Tokyo": ((40.7128, -74.0060), (35.6762, 139.6503)),
"equator, due east": ((0.0, 0.0), (0.0, 10.0))}
for name, (p, q) in routes.items():
b = bearing(p, q)
print(f"{name:26} {b:6.1f} deg {compass(b)}")Hanoi -> Ho Chi Minh City 175.7 deg S
London -> Paris 148.1 deg SE
New York -> Tokyo 333.0 deg NW
equator, due east 90.0 deg E
New York to Tokyo starts out heading north-northwest (333°), up over Canada and Alaska, even though Tokyo looks almost due west on a flat map. That is the great circle at work.
In software
- Location apps: "drivers within 2 km" filters candidates with a cheap bounding box in degrees, then ranks them with haversine.
- Databases: PostGIS and MongoDB geospatial queries do these calculations; knowing the formula helps you choose the right index and units.
- Games with planet maps: distances and travel times between cities on a globe.
- Map tiles: web maps use the Mercator projection, which also stretches by : Greenland looks as big as Africa.
Exercises
Exercise 1: Degree lengths
How long is one degree of longitude at the equator, at 45° and at 60° latitude ()?
Answer
About 111.19 km, 78.63 km and 55.60 km.
Solution
Exercise 2: A quarter of the equator
Use the haversine formula by hand for and . Does the answer make sense?
Answer
, a quarter of the equator's length.
Solution
The equator is long, and 90° is a quarter of it. ✓
Exercise 3: The nearest café (code)
You are at (48.8584, 2.2945). Which of these cafés is nearest by haversine distance, and how far is it in metres: A (48.8606, 2.3376), B (48.8530, 2.3499), C (48.8738, 2.2950)?
Answer
Café C, about 1 713 m away.
Solution
C is almost due north, 0.0154° of latitude away: by the flat estimate, 1 713 m by haversine. A and B are 3 km or more to the east.
import math
R = 6371000.0
def haversine(p, q):
f1, l1, f2, l2 = map(math.radians, (*p, *q))
a = math.sin((f2 - f1) / 2)**2 + math.cos(f1) * math.cos(f2) * math.sin((l2 - l1) / 2)**2
return 2 * R * math.asin(math.sqrt(a))
me = (48.8584, 2.2945)
cafes = {"A": (48.8606, 2.3376), "B": (48.8530, 2.3499), "C": (48.8738, 2.2950)}
for name, pos in sorted(cafes.items(), key=lambda kv: haversine(me, kv[1])):
print(name, round(haversine(me, pos)))C 1713
A 3162
B 4097
Exercise 4: Due east?
At latitude 45° N you start walking along the great circle with an initial bearing of exactly 90° (due east). Is your latitude constant along the way?
Answer
No. Only the equator is a great circle that runs east–west. A great circle that starts due east at 45° N curves south and crosses the equator.
Solution
A circle of latitude at 45° has radius , smaller than , so it is not a great circle and not the shortest path. The great circle heading east from 45° N is tilted relative to the equator: your latitude decreases, and you cross the equator a quarter of the way round the Earth (10 000 km later).
Test yourself
Why does 1° of longitude get shorter toward the poles?
- Earth spins faster there
- The circle of latitude has radius
- Longitude is measured in hours
- Maps stretch it
Which route does the naive 'Pythagoras on degrees' formula handle best?
- An east–west route near the Arctic
- A route crossing the Pacific
- A north–south route
- Any route over 5000 km
What does the haversine formula compute?
- The great-circle distance between two points on a sphere
- The straight-line tunnel distance through the Earth
- The distance along a line of constant bearing
- The distance on a Mercator map