How to compute distance and bearing between two lat/lon points in Python
Problem:
Let’s assume we have the following points represented by their latitude & longitude in Python:
a = (48.11617185, 11.743858785932662)
b = (48.116026149999996, 11.743938922310974)
and we want to compute both distance and bearing between those points on the WGS84 or any other Geoid of your choosing.
Solution
We can use geographiclib to do that:
from geographiclib.geodesic import Geodesic
result = Geodesic.WGS84.Inverse(*a, *b)
distance = result["s12"] # in [m] (meters)
bearing = result["azi1"] # in [°] (degrees)
Geodesic.WGS84.Inverse(*a, *b)
is just a shorthand for Geodesic.WGS84.Inverse(a[0], a[1], b[0], b[1])
, so don’t be too confused by the syntax.
Using our example coordinates from above result
is
{'lat1': 48.11617185,
'lon1': 11.743858785932662,
'lat2': 48.116026149999996,
'lon2': 11.743938922310974,
'a12': 0.00015532346032069415,
's12': 17.26461706032189,
'azi1': 159.78110567187977,
'azi2': 159.7811653333465}
Therefore,
distance = 17.26461706032189 # m
bearing = 159.78110567187977 # °