TExcelTAD
Home › Pre-Calculus, Geometry & Trigonometry › Map Distances and the Haversine Formula

Map Distances and the Haversine Formula

GPS gives positions as latitude and longitude: angles on a sphere, not xx and yy 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 φ\varphi (north–south, −90° to 90°) and longitude λ\lambda (east–west, −180° to 180°). Model Earth as a sphere of radius R≈6371 kmR \approx 6371\ \text{km}. Then:

  • One degree of latitude is always 2πR/360≈111.19 km2\pi R/360 \approx 111.19\ \text{km}.
  • One degree of longitude shrinks toward the poles: the circle of latitude φ\varphi has radius Rcos⁡φR\cos\varphi, so a degree of longitude is 111.19cos⁡φ km111.19\cos\varphi\ \text{km}. At 60° north it is only half as long as at the equator.

That cos⁡φ\cos\varphi 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 RR 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:

Δφ=φ2−φ1,Δλ=λ2−λ1(all in radians)a=sin⁡2(Δφ/2)+cos⁡φ1⋅cos⁡φ2⋅sin⁡2(Δλ/2)d=2R⋅arcsin⁡(a)\begin{aligned} &\Delta\varphi = \varphi_2 - \varphi_1, \quad \Delta\lambda = \lambda_2 - \lambda_1 && \text{(all in radians)} \\ &a = \sin^2(\Delta\varphi/2) + \cos\varphi_1 \cdot \cos\varphi_2 \cdot \sin^2(\Delta\lambda/2) \\ &d = 2R \cdot \arcsin(\sqrt{a}) \end{aligned}

It comes from the spherical law of cosines, rewritten with hav⁡(θ)=sin⁡2(θ/2)=(1−cos⁡θ)/2\operatorname{hav}(\theta) = \sin^2(\theta/2) = (1 - \cos\theta)/2 so that small angles do not lose their digits to cos⁡θ≈1\cos\theta \approx 1 (compare the law of cosines in the plane). The name is old: "haversine" is half of the versine, 1−cos⁡θ1 - \cos\theta, 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:

x=Δλ⋅cos⁡φ1+φ22,y=Δφ,d≈R⋅x2+y2x = \Delta\lambda \cdot \cos\frac{\varphi_1 + \varphi_2}{2}, \qquad y = \Delta\varphi, \qquad d \approx R \cdot \sqrt{x^2 + y^2}

It is cheap (one cos⁡\cos, 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.

python · try it yourself
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 [−180∘,180∘)[-180^\circ, 180^\circ), which is what dlon does; haversine does not, because sin⁡2(Δλ/2)\sin^2(\Delta\lambda/2) 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 (0∘=north0^\circ = \text{north}, 90∘=east90^\circ = \text{east}), measured clockwise:

θ=atan2⁡(sin⁡Δλ⋅cos⁡φ2, cos⁡φ1⋅sin⁡φ2−sin⁡φ1⋅cos⁡φ2⋅cos⁡Δλ)bearing=(degrees⁡(θ)+360) mod 360\begin{aligned} \theta &= \operatorname{atan2}(\sin\Delta\lambda \cdot \cos\varphi_2,\ \cos\varphi_1 \cdot \sin\varphi_2 - \sin\varphi_1 \cdot \cos\varphi_2 \cdot \cos\Delta\lambda) \\ \text{bearing} &= (\operatorname{degrees}(\theta) + 360) \bmod 360 \end{aligned}

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.

python · try it yourself
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 1/cos⁡φ1/\cos\varphi: 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 (R=6371 kmR = 6371\ \text{km})?

Answer

About 111.19 km, 78.63 km and 55.60 km.

Solution
equator:2π⋅6371/360≈111.19 km45∘:111.19⋅cos⁡45∘≈111.19⋅0.7071≈78.63 km60∘:111.19⋅cos⁡60∘=111.19⋅0.5≈55.60 km\begin{aligned} &\text{equator:} && 2\pi \cdot 6371/360 \approx 111.19\ \text{km} \\ &45^\circ{:} && 111.19 \cdot \cos 45^\circ \approx 111.19 \cdot 0.7071 \approx 78.63\ \text{km} \\ &60^\circ{:} && 111.19 \cdot \cos 60^\circ = 111.19 \cdot 0.5 \approx 55.60\ \text{km} \end{aligned}

Exercise 2: A quarter of the equator

Use the haversine formula by hand for (0∘,0∘)(0^\circ, 0^\circ) and (0∘,90∘)(0^\circ, 90^\circ). Does the answer make sense?

Answer

d=πR/2≈10 007.5 kmd = \pi R/2 \approx 10\,007.5\ \text{km}, a quarter of the equator's length.

Solution
Δφ=0,Δλ=π/2,cos⁡φ1=cos⁡φ2=1a=0+1⋅1⋅sin⁡2(π/4)=(2/2)2=1/2d=2R⋅arcsin⁡(1/2)=2R⋅(π/4)=πR/2≈10 007.5 km\begin{aligned} &\Delta\varphi = 0, \quad \Delta\lambda = \pi/2, \quad \cos\varphi_1 = \cos\varphi_2 = 1 \\ &a = 0 + 1 \cdot 1 \cdot \sin^2(\pi/4) = (\sqrt{2}/2)^2 = 1/2 \\ &d = 2R \cdot \arcsin\left(\sqrt{1/2}\right) = 2R \cdot (\pi/4) = \pi R/2 \approx 10\,007.5\ \text{km} \end{aligned}

The equator is 2πR≈40 030 km2\pi R \approx 40\,030\ \text{km} 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: 0.0154⋅111 195 m≈1 712 m0.0154 \cdot 111\,195\ \text{m} \approx 1\,712\ \text{m} by the flat estimate, 1 713 m by haversine. A and B are 3 km or more to the east.

python · try it yourself
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 Rcos⁡45∘R\cos 45^\circ, smaller than RR, 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?

  1. Earth spins faster there
  2. The circle of latitude φ\varphi has radius Rcos⁡φR\cos\varphi
  3. Longitude is measured in hours
  4. Maps stretch it

Which route does the naive 'Pythagoras on degrees' formula handle best?

  1. An east–west route near the Arctic
  2. A route crossing the Pacific
  3. A north–south route
  4. Any route over 5000 km

What does the haversine formula compute?

  1. The great-circle distance between two points on a sphere
  2. The straight-line tunnel distance through the Earth
  3. The distance along a line of constant bearing
  4. The distance on a Mercator map