1
+ '''
2
+ Work out the distance (user specified units) given two cities using haversine equation
3
+ '''
4
+
5
+ from pygeocoder import Geocoder
6
+ import numpy as np
7
+ import sys
8
+
9
+ def get_distance (locA , locB ):
10
+ #use haversine forumla
11
+ earth_rad = 6371.0
12
+ dlat = np .deg2rad (locB [0 ] - locA [0 ])
13
+ dlon = np .deg2rad (locB [1 ] - locA [1 ])
14
+ a = np .sin (dlat / 2 ) * np .sin (dlat / 2 ) + \
15
+ np .cos (np .deg2rad (locA [0 ])) * np .cos (np .deg2rad (locB [0 ])) * \
16
+ np .sin (dlon / 2 ) * np .sin (dlon / 2 )
17
+ c = 2 * np .arctan2 (np .sqrt (a ), np .sqrt (1 - a ))
18
+ return earth_rad * c
19
+
20
+ def get_latlongs (location ):
21
+ return Geocoder .geocode (location )[0 ].coordinates
22
+
23
+ def convert_km_to_miles (km ):
24
+ miles_per_km = 0.621371192
25
+ return km * miles_per_km
26
+
27
+ def main ():
28
+ #get first city
29
+ print 'Type the first City: '
30
+ cityA = raw_input ()
31
+
32
+ #get second city
33
+ print 'Type the second city: '
34
+ cityB = raw_input ()
35
+
36
+ #get units
37
+ units = ''
38
+ while (units != 'km' ) & (units != 'm' ):
39
+ print 'Type distance units (miles or kilometers): '
40
+ units = str .lower (raw_input ())
41
+ if units in ['clicks' , 'km' , 'kilometers' , 'kilometer' ]:
42
+ units = 'km'
43
+ elif units in ['m' , 'mile' , 'miles' ]:
44
+ units = 'm'
45
+ else :
46
+ print 'units not recognised, please try again'
47
+
48
+ #find the distance in km
49
+ try :
50
+ distance = get_distance (get_latlongs (cityA ),
51
+ get_latlongs (cityB ))
52
+ #display the distance
53
+ if units == 'km' :
54
+ print str (distance ),' km'
55
+ else :
56
+ distance = convert_km_to_miles (distance )
57
+ print str (distance ), ' miles'
58
+
59
+ except :
60
+ print 'Error raised. Are the input cities correct?'
61
+
62
+
63
+ if __name__ == '__main__' :
64
+ sys .exit (main ())
0 commit comments