|
| 1 | +""" |
| 2 | +Distance Between Two Cities |
| 3 | +- Calculates the distance between two cities and allows the user to specify |
| 4 | +a unit of distance. This program may require finding coordinates for the |
| 5 | +cities like latitude and longitude. |
| 6 | +
|
| 7 | +This will require you to download the geopy module located here: |
| 8 | +- https://code.google.com/p/geopy/ |
| 9 | +- pip install geopy |
| 10 | +
|
| 11 | +It uses the Haversine formula to find an approximate distance between the points. |
| 12 | +- http://en.wikipedia.org/wiki/Haversine_formula |
| 13 | +
|
| 14 | +Call By |
| 15 | +- python |
| 16 | +- from _numbers.distance import distance |
| 17 | +- distance() |
| 18 | +
|
| 19 | +""" |
| 20 | +from geopy import geocoders |
| 21 | +import math |
| 22 | + |
| 23 | + |
| 24 | +def distance(): |
| 25 | + point1 = raw_input('Enter a city and state ex: \'Tampa, FL\': ') |
| 26 | + point2 = raw_input('Enter another city and state ex: \'Tampa, FL\': ') |
| 27 | + |
| 28 | + # Convert the typed locations to coordinates |
| 29 | + try: |
| 30 | + g = geocoders.GoogleV3() |
| 31 | + place1, (lat1, lng1) = g.geocode(point1) |
| 32 | + place2, (lat2, lng2) = g.geocode(point2) |
| 33 | + |
| 34 | + # Radians measurements for angles |
| 35 | + lat1 = math.radians(lat1) |
| 36 | + lat2 = math.radians(lat2) |
| 37 | + lng1 = math.radians(lng1) |
| 38 | + lng2 = math.radians(lng2) |
| 39 | + |
| 40 | + # Haversine Formula |
| 41 | + a = (1 - math.cos((2 * (lat2 - lat1)) / 2.0)) / 2.0 |
| 42 | + b = math.cos(lat1) * math.cos(lat2) |
| 43 | + c = (1 - math.cos((2 * (lng2 - lng1)) / 2.0)) / 2.0 |
| 44 | + d = math.sqrt(abs(a + (b * c))) |
| 45 | + e = 2 * 6371 * math.asin(d) |
| 46 | + |
| 47 | + while True: |
| 48 | + output = raw_input('What units would you like the distance in? (Miles = M, Kilometers = KM): ').lower() |
| 49 | + |
| 50 | + if output not in ['m', 'km']: |
| 51 | + print 'Choose between K and M, please.' |
| 52 | + else: |
| 53 | + break |
| 54 | + |
| 55 | + if output == 'km': |
| 56 | + print '\nThe distance between {} and {} is:'.format(place1, place2) |
| 57 | + print '{0:.2f} km'.format(e) |
| 58 | + else: |
| 59 | + miles = e * 0.621371192 |
| 60 | + print '\nThe distance between {} and {} is:'.format(place1, place2) |
| 61 | + print '{0:.2f} miles'.format(miles) |
| 62 | + |
| 63 | + except (ValueError, geocoders.base.GeocoderError): |
| 64 | + print 'We couldn\'t find one of those locations!' |
0 commit comments