Saturday 9 July 2016

TrafficControl: Calculating Distances between Coordinates on the Surface of a Sphere

Distance calculations will be essential for the TrafficControl program. In a flat world, Pythagoras theorem would do just fine, but the calculations will be done on the surface of a sphere.

Starting from Paris, moving 2000 km north and after that 1000 km to the east, you will end up close to Rovaniemi, Finland. Moving 1000 km east from Paris and then 2000 km north, you will end up south of the national park of Sarek, 400 km off. This happens as the distance around the world along a certain latitude is smaller when moving away from the equator.

The Haversine formula takes all this into account. The implementation I use is:

def haversine(lon1, lat1, lon2, lat2):  #From rosettacode.org

  R = 6372.8 # Earth radius in kilometers
  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

Here, the distance between the coordinates (lon1, lat1) and (lon2, lat2) is R*c.

Keep in mind to check whether the coordinates are sent with longitude first and latitude last or the other way around. That will reduce the risk of tricky bugs.

No comments:

Post a Comment