geocoding.py 890 B

12345678910111213141516171819202122232425262728293031
  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. def k_neighbors(positions, fro, n):
  22. """returns a list of (dist, id) of the n nearest points from fro
  23. positions is a dictionary id -> (lat, long)"""
  24. distances = sorted([(dist(fro, pos), id) for (id, pos) in positions.items()])
  25. return distances[:n]