Monday, June 15, 2009

Get the distance between two latitude/longitude points in km (example)

Here is a python script to convert lat/lng point to meters. It expects the points to be entered in as decimal degrees. It outputs the distance in km.

For example:

python distlatlng.py 36.12 -86.67 33.94 -118.40
the distance in km is 2887.25995061



#uses the haversine formula
# based on code from http://www.movable-type.co.uk/scripts/latlong.html
import math, sys

def main(*args):
if len(args) < 5:
print args[0]," lng1 lat1 lng2 lat2 (finds distance between two lat/lng pairs)"
return
lat1 = float(args[1])
lng1 = float(args[2])
lat2 = float(args[3])
lng2 = float(args[4])
radius = 6372.8 # earth's mean radium in km
dlat = math.radians(lat2-lat1)
dlng = math.radians(lng2-lng1)
a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlng/2)*math.sin(dlng/2)
c = 2*math.atan2(math.sqrt(a),math.sqrt(1-a))
dist = radius*c
print "the distance in km is " , dist


if __name__ == "__main__":
main(*sys.argv)


No comments:

Post a Comment