-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdistance.py
67 lines (52 loc) · 1.52 KB
/
distance.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""
Problem
-------
**Distance Between Two Cities**
Calculates the distance between two cities
and allows the user to specify a unit of
distance. This program may require finding
coordinates for the cities like latitude
and longitude.
Solution
--------
solution found using the geopy library
Author
------
dbonadiman
"""
import sys
from math import fabs, acos, pi, sin, cos, radians
from geopy import geocoders
def geo_distance(a, b):
"""
This calculate the distance between two geographical
coordinates
>>> geo_distance((46.06, 11.12), (46.49, 11.35))
47.81381845713197
"""
R = 6371 # Earth radius
a_rad = (radians(a[0]), radians(a[1]))
b_rad = (radians(b[0]), radians(a[1]))
fi = fabs(a_rad[1] - b_rad[1])
p = acos(sin(b_rad[0]) * sin(a_rad[0])
+ cos(b_rad[0]) * cos(a_rad[0]) * cos(fi))
return p*R
def main():
try:
print("\nThis program calculate the distance between two city\n"
"Please enter the name of the cities:\n")
gn = geocoders.GoogleV3()
city1 = gn.geocode(raw_input("--> "), exactly_one=False)[0]
city2 = gn.geocode(raw_input("--> "), exactly_one=False)[0]
print("\nthe distance between {} and {} "
"is : {} m").format(city1[0], city2[0],
geo_distance(city1[1], city2[1]))
return 0
except Exception, e:
print(e)
return 1
if __name__ == "__main__":
import doctest
doctest.testmod()
status = main()
sys.exit(status)