Skip to content

Instantly share code, notes, and snippets.

@pwldp
Last active August 29, 2015 14:02
Show Gist options
  • Save pwldp/88fa777e6ca11d5b85f4 to your computer and use it in GitHub Desktop.
Save pwldp/88fa777e6ca11d5b85f4 to your computer and use it in GitHub Desktop.
calculate distance between two points on earth, result in meters
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# calculate distance between two points on earth, result in meters
#
# based on: http://stackoverflow.com/questions/4716017/django-how-can-i-find-the-distance-between-two-locations
# check distance at: http://www.distancefromto.net/
#
# Dariusz Pawlak <pawlakdp@gmail.com>
# 2014.06.12
#
#
from math import sin, cos, radians, acos
import math
# http://en.wikipedia.org/wiki/Earth_radius
# """For Earth, the mean radius is 6,371.009 km (˜3,958.761 mi; ˜3,440.069 nmi)"""
EARTH_RADIUS_IN_MILES = 3958.761
def calc_dist(lat_a, long_a, lat_b, long_b):
"""all angles in degrees, result in kilometers"""
lat_a = radians(lat_a)
lat_b = radians(lat_b)
delta_long = radians(long_a - long_b)
cos_x = (
sin(lat_a) * sin(lat_b) +
cos(lat_a) * cos(lat_b) * cos(delta_long)
)
return int( ((acos(cos_x) * EARTH_RADIUS_IN_MILES) / 0.62137) * 1000)
"""
based on: https://github.com/willcalderbank/Python-tests/blob/master/distance-from-points.py
"""
def calculate_distance((lat1,lon1), (lat2,lon2)):
R = 6371 # km
dLat = math.radians(math.fabs(lat2-lat1))
dLon = math.radians(math.fabs(lon2-lon1))
lat1 = math.radians(lat1)
lat2 = math.radians(lat2)
a = math.sin(dLat/2) * math.sin(dLat/2) + math.sin(dLon/2) * math.sin(dLon/2) * math.cos(lat1) * math.cos(lat2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
return R * c
if __name__ == "__main__":
print "odleglosc"
"""
(50.3404,18.8923) -> (53.1229,18.0689)
=>> distance 314.548529868 km
"""
print calc_dist( 50.3404,18.8923,53.1229,18.0689)
print calculate_distance( (50.3404,18.8923),(53.1229,18.0689))
#
# EOF
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment