I tried implementing this formula: http://andrew.hedges.name/experiments/haversine/ The aplet does good for the two points I am testing:
Yet my code is not working.
from math import sin, cos, sqrt, atan2
R = 6373.0
lat1 = 52.2296756
lon1 = 21.0122287
lat2 = 52.406374
lon2 = 16.9251681
dlon = lon2 - lon1
dlat = lat2 - lat1
a = (sin(dlat/2))**2 + cos(lat1) * cos(lat2) * (sin(dlon/2))**2
c = 2 * atan2(sqrt(a), sqrt(1-a))
distance = R * c
print "Result", distance
print "Should be", 278.546
The distance it returns is 5447.05546147. Why?
Update: 04/2018: Note that Vincenty distance is deprecated since GeoPy version 1.13 - you should use geopy.distance.distance() instead!
The answers above are based on the Haversine formula, which assumes the earth is a sphere, which results in errors of up to about 0.5% (according to help(geopy.distance)
). Vincenty distance uses more accurate ellipsoidal models such as WGS-84, and is implemented in geopy. For example,
import geopy.distance
coords_1 = (52.2296756, 21.0122287)
coords_2 = (52.406374, 16.9251681)
print geopy.distance.vincenty(coords_1, coords_2).km
will print the distance of 279.352901604
kilometers using the default ellipsoid WGS-84. (You can also choose .miles
or one of several other distance units).