Last active
August 29, 2015 14:12
-
-
Save maxrp/b9a8c31fc3413fbbed93 to your computer and use it in GitHub Desktop.
Another python haversine implementation
This file contains hidden or 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
#!/usr/bin/env python | |
import math | |
# from here: https://gist.github.com/rochacbruno/2883505 | |
def distance(origin, destination): | |
lat1, lon1 = origin | |
lat2, lon2 = destination | |
radius = 6371 # km | |
dlat = math.radians(lat2-lat1) | |
dlon = math.radians(lon2-lon1) | |
a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \ | |
* math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2) | |
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a)) | |
d = radius * c | |
return d | |
# from here: https://github.com/mapado/haversine/blob/master/haversine/__init__.py | |
def py_haversine(point1, point2, miles=False): | |
""" Calculate the great-circle distance bewteen two points on the Earth surface. | |
:input: two 2-tuples, containing the latitude and longitude of each point | |
in decimal degrees. | |
Example: haversine((45.7597, 4.8422), (48.8567, 2.3508)) | |
:output: Returns the distance bewteen the two points. | |
The default unit is kilometers. Miles can be returned | |
if the ``miles`` parameter is set to True. | |
""" | |
# unpack latitude/longitude | |
lat1, lng1 = point1 | |
lat2, lng2 = point2 | |
# convert all latitudes/longitudes from decimal degrees to radians | |
lat1, lng1, lat2, lng2 = list(map(math.radians, [lat1, lng1, lat2, lng2])) | |
# calculate haversine | |
lat = lat2 - lat1 | |
lng = lng2 - lng1 | |
d = math.sin(lat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(lng / 2) ** 2 | |
h = 2 * 6371 * math.asin(math.sqrt(d)) | |
if miles: | |
return h * 0.621371 # in miles | |
else: | |
return h # in kilometers | |
def my_hvsin(start, finish, r=6371): | |
# convert input tuples to radians | |
lat1, lon1 = map(math.radians, start) | |
lat2, lon2 = map(math.radians, finish) | |
haversine = lambda x: math.sin(x/2)**2 # define ha(lf-)versine | |
# calculate the haversines of the deltas between start and end | |
dlat, dlon = (haversine(lat2 - lat1), haversine(lon2 - lon1)) | |
d = 2*r*math.asin(math.sqrt(dlat + math.cos(lat1) * math.cos(lat2) * dlon)) | |
return d | |
# examples | |
print distance((45.31, 122.40), (47.36, 122.19)) | |
print py_haversine((45.31, 122.40), (47.36, 122.19)) | |
print my_hvsin((45.31, 122.40), (47.36, 122.19)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FYI the function my_hvsin(start,finish,r=6371) should be construed as public domain code.