vegaseat

distance between two cities

Mar 13th, 2015
326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. ''' distance_longitude_latitude101.py
  2. given the longitudes and latitudes of two cities, calculate the distance
  3.  
  4. Uses the Haversine Formula recommended for calculating short
  5. distances by NASA's Jet Propulsion Laboratory.  For longer
  6. distances this formula tends to overestimate trans-polar distances and
  7. underestimate trans-equatorial distances.
  8.  
  9. tested with Python27 and Python34  by  vegaseat  19jan2015
  10. '''
  11.  
  12. from math import radians, cos, sin, asin, sqrt
  13.  
  14. def haversine(lon1, lat1, lon2, lat2):
  15.     '''
  16.    calculate the great circle distance between two points
  17.    on the Earth (coordinates specified in decimal degrees)
  18.    '''
  19.     # convert decimal degrees to radians
  20.     lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
  21.  
  22.     # Haversine formula
  23.     dlon = lon2 - lon1
  24.     dlat = lat2 - lat1
  25.     a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
  26.     c = 2 * asin(sqrt(a))
  27.  
  28.     # 6367 km (3961 miles) is the radius of the Earth
  29.     km = 6367 * c
  30.     miles = 3961 * c
  31.     return km, miles
  32.  
  33.  
  34. # Detroit, Michigan  48235
  35. city1 = "Detroit"
  36. lat1  = 42.4261
  37. lon1 = -83.1951
  38.  
  39. # Chicago, Illinois  60290
  40. city2 = "Chicago"
  41. lat2  = 41.9613
  42. lon2 = -87.8849
  43.  
  44. km, miles = haversine(lon1, lat1, lon2, lat2)
  45.  
  46. sf = "The distance between {} and {} is {:0.1f} miles (air)"
  47. print(sf.format(city1, city2, miles))
  48.  
  49. ''' result ...
  50. The distance between Detroit and Chicago is 242.3 miles (air)
  51. '''
Advertisement
Add Comment
Please, Sign In to add comment