Geocode cities & display randomly with Leaflet

nomnom-gc.py 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import io
  2. import requests
  3. import os.path
  4. import time
  5. import shutil
  6. print "Going to delete all contents of geocoded-cities.txt and creating a backup named 'geocoded-cities_back.txt'"
  7. time.sleep(2) # little delay for reading
  8. # check if file exists, if yes copy to backup and empty it
  9. if os.path.isfile('geocoded-cities.txt')==True:
  10. shutil.copy2('geocoded-cities.txt', 'geocoded-cities_back.txt')
  11. with open('geocoded-cities.txt', 'w+') as ft:
  12. ft.truncate()
  13. ft.close()
  14. # empty logfile
  15. with open('geocode.log', 'w+') as fl:
  16. fl.truncate()
  17. fl.close()
  18. with open('cities.txt') as fp:
  19. for city in fp:
  20. try:
  21. payload = {'format': 'json', 'q': ' '}
  22. payload['q'] = city
  23. r = requests.get('http://open.mapquestapi.com/nominatim/v1/search', params=payload)
  24. placesjson = {}
  25. placesjson = r.json()
  26. firstResult = placesjson[0] # nominatim delivers (depending on input) multiple resultsets, first one should be the desired
  27. with open('geocoded-cities.txt', 'aw+') as fgeo:
  28. fgeo.write("%s, %s, %s\n" % (city.rstrip(), firstResult['lat'], firstResult['lon']))
  29. print "Status [OK]: %s, %s, %s" % (city.rstrip(), firstResult['lat'], firstResult['lon'])
  30. with open('geocode.log', 'aw+') as flog:
  31. flog.write("Status [OK]: %s, %s, %s\n" % (city.rstrip(), firstResult['lat'], firstResult['lon']))
  32. except:
  33. print "Status[Not Found]: %s" % city.rstrip()
  34. with open('geocode.log', 'aw+') as flog:
  35. flog.write("Status [Not Found]: %s\n" % city.rstrip())
  36. fgeo.close()
  37. fp.close()
  38. flog.close()