Created
October 5, 2013 07:21
-
-
Save matbor/6837804 to your computer and use it in GitHub Desktop.
Simple python script to find the line of sight distance between two sets of latitude and longitude points. Will modified later for geofencing with mqttitude.org backend server.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
def distance_on_unit_sphere(lat1, long1, lat2, long2): | |
# 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 | |
# 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 #setting to kilometers here | |
return arc | |
#example | |
#lon, lat | |
#145.329013,-37.913301 location #1 | |
#144.940333,-37.832111 location #2 | |
lon1a = 145.329013 | |
lat1a = -37.913301 | |
lon2b = 144.940333 | |
lat2b = -37.832111 | |
print str('%.2f' % 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