geocoding.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. from geopy.geocoders import Nominatim
  2. from geopy.distance import vincenty
  3. from source import *
  4. geolocator = Nominatim()
  5. def position_of_location(location):
  6. """returns a pair (latitude, longitude) from an adress
  7. or None if not possible"""
  8. try:
  9. pos = geolocator.geocode(location)
  10. return (pos.latitude, pos.longitude)
  11. except:
  12. return None
  13. def dist(posa, posb):
  14. """compute the distance between two position (pair latitude, longitude)
  15. in kilometers
  16. or None if one of the argument is None"""
  17. if not posa or not posb:
  18. return None
  19. else:
  20. return vincenty(posa, posb).km
  21. p1 = position_of_location("22 rue Henri Barbusse VILLEJUIF")
  22. #p2 = position_of_location("Université paris diderot")
  23. #print(p1, p2, dist(p1, p2))
  24. def k_neighbors(positions, fro, n):
  25. """returns a list of (dist, id) of the n nearest points from fro
  26. positions is a dictionary id -> (lat, long)"""
  27. distances = sorted([(dist(fro, pos), id) for (id, pos) in positions.items()])
  28. return distances[:n]
  29. res = k_neighbors(SourceProvider_jcdecaux_vls().dic_of_positions(), p1, 5)
  30. names = SourceProvider_jcdecaux_vls().dic_of_names()
  31. for (dist, id) in res:
  32. print(names[id] + ' at ' + str(dist) + 'km')