Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Wednesday, December 16, 2009

Latitude longitude distance calculation

The python code for calculating the distance between 2 locations, given their latitude & longitude (in degrees), using the Haversine method. The output is in meters.


import math, cmath

def getDist(lat2,lng2,lat1,lng1):
   lat1 = math.radians(lat1)
   lat2 = math.radians(lat2)
   lng1 = math.radians(lng1)
   lng2 = math.radians(lng2)
   dlat = lat2 - lat1
   dlng = lng2 - lng1
   a = math.pow(cmath.sin(dlat*0.5).real,2) + cmath.cos(lat1).real * cmath.cos(lat2).real * math.pow(cmath.sin(dlng*0.5).real,2)
   d = 2 * cmath.asin(math.sqrt(a)).real
   dist = d * 6378137
   return dist

usage:

   d = getDist(45.6738037,-122.6812485, 47.6062095,-122.3320708)