Skip to content

Instantly share code, notes, and snippets.

@matbor
Last active December 26, 2015 12:39
Show Gist options
  • Save matbor/7152469 to your computer and use it in GitHub Desktop.
Save matbor/7152469 to your computer and use it in GitHub Desktop.
Handy example for working out distance between two sets of latitude and longitude points.... The start of a geo fence!
import math
def distance_on_unit_sphere(lat1, long1, lat2, long2):
# modified by Matthew Bordignon @bordignon Oct 2013
#
# handy example for finding distance between two sets of co-oridinates
# modified from http://www.johndcook.com/python_longitude_latitude.html
# handy tool to chk calculations, http://www.johndcook.com/lat_long_distance.html
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
arc = math.acos( cos )
# Remember to multiply arc by the radius of the earth
# in your favorite set of units to get length.
# We assume the radius of the earth is 3960 miles or 6373 kilometers
arc = arc * 6373 #kilometers here
#arc = arc * 3960 #miles here
arc = '%.1f' % arc #reduce to one deciminal point
return arc
#example on how to use it
#home
lon1a = 145.359013
lat1a = -37.913301
#work
lon2b = 144.950333
lat2b = -37.832111
print str(distance_on_unit_sphere(lat1a, lon1a, lat2b, lon2b)) +" kilometers between the two points"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment