/
city_distance.py
68 lines (53 loc) · 1.75 KB
/
city_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
68
'''
Work out the distance (user specified units) given two cities using haversine equation
'''
from pygeocoder import Geocoder
import numpy as np
import sys
def get_distance(locA, locB):
# use haversine forumla
earth_rad = 6371.0
dlat = np.deg2rad(locB[0] - locA[0])
dlon = np.deg2rad(locB[1] - locA[1])
a = np.sin(dlat / 2) * np.sin(dlat / 2) + \
np.cos(np.deg2rad(locA[0])) * np.cos(np.deg2rad(locB[0])) * \
np.sin(dlon / 2) * np.sin(dlon / 2)
c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a))
return earth_rad * c
def get_latlongs(location):
return Geocoder.geocode(location)[0].coordinates
def convert_km_to_miles(km):
miles_per_km = 0.621371192
return km * miles_per_km
def main():
# get first city
print("Type the first City: ")
cityA = input()
# get second city
print ("Type the second city: ")
cityB = input()
# get units
units = ''
while (units != 'km') & (units != 'm'):
print ("Type distance units (miles or kilometers): ")
units = str.lower(input())
if units in ['clicks', 'km', 'kilometers', 'kilometer']:
units = 'km'
elif units in ['m', 'mile', 'miles']:
units = 'm'
else:
print("units not recognised, please try again")
# find the distance in km
try:
distance = get_distance(get_latlongs(cityA),
get_latlongs(cityB))
# display the distance
if units == 'km':
print(str(distance), ' km')
else:
distance = convert_km_to_miles(distance)
print(str(distance), ' miles')
except:
print("Error raised. Are the input cities correct?")
if __name__ == '__main__':
sys.exit(main())