Occasionally, I have to calculate the distance between two sets of coordinates. This was a very complex task for me when I first started coding, as I had no clue how it all worked, how the math worked, or what libraries would even help me.

Lots of this was always done through Python projects, specifically on Django. I had to rely heavily on GeoDjango when I first learned it. It made things a bit convenient but was always challenging to set up.

So today, I’m going to share a formula I’ve used a lot after learning it. The haversine formula.

From Wiki itself:

“The haversine formula determines the great-circle distance between two points on a sphere given their longitudes and latitudes. Important in navigation, it is a special case of a more general formula in spherical trigonometry, the law of haversines, that relates the sides and angles of spherical triangles.”

Wikipedia – https://en.wikipedia.org/wiki/Haversine_formula

So if you are in need of calculating the distance (in miles) between two set of coordinates in Python, here is one of the best written functions I’ve found to date.

from math import radians, cos, sin, asin, sqrt

def haversine(lat1, lon1, lat2, lon2):

      R = 3959.87433 # this is in miles.  For Earth radius in kilometers use 6372.8 km

      dLat = radians(lat2 - lat1)
      dLon = radians(lon2 - lon1)
      lat1 = radians(lat1)
      lat2 = radians(lat2)

      a = sin(dLat/2)**2 + cos(lat1)*cos(lat2)*sin(dLon/2)**2
      c = 2*asin(sqrt(a))

      return R * c

The source comes from jwinn’s response on StackOverflow here https://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points.

Author

My name is Tony, and I’m an Experience Designer with 8+ years of experience in design and development. At heart, I am a developer first and a designer second. I enjoy creating interactive experiences, but I also enjoy designing and learning about the user’s experiences.

Write A Comment