Posted By

atr000 on 05/23/09


Tagged

python maps geocode


Versions (?)

Python: geocode address via urllib


 / Published in: Python
 

URL: http://canadianamp.ca/2008/12/05/simple-geocoding-with-python-and-urllib/

  1. import urllib,urllib2,time
  2. addr_file = 'addresses.csv'
  3. out_file = 'addresses_geocoded.csv'
  4. out_file_failed = 'failed.csv'
  5. sleep_time = 2
  6. root_url = "http://maps.google.com/maps/geo?"
  7. gkey = "YourGoogleKeyGoesHere"
  8. return_codes = {'200':'SUCCESS',
  9. '400':'BAD REQUEST',
  10. '500':'SERVER ERROR',
  11. '601':'MISSING QUERY',
  12. '602':'UNKOWN ADDRESS',
  13. '603':'UNAVAILABLE ADDRESS',
  14. '604':'UNKOWN DIRECTIONS',
  15. '610':'BAD KEY',
  16. '620':'TOO MANY QUERIES'
  17. }
  18. def geocode(addr,out_fmt='csv'):
  19. #encode our dictionary of url parameters
  20. values = {'q' : addr, 'output':out_fmt, 'key':gkey}
  21. data = urllib.urlencode(values)
  22. #set up our request
  23. url = root_url+data
  24. req = urllib2.Request(url)
  25. #make request and read response
  26. response = urllib2.urlopen(req)
  27. geodat = response.read().split(',')
  28. response.close()
  29. #handle the data returned from google
  30. code = return_codes[geodat[0]]
  31. if code == 'SUCCESS':
  32. code,precision,lat,lng = geodat
  33. return {'code':code,'precision':precision,'lat':lat,'lng':lng}
  34. else:
  35. return {'code':code}
  36. def main():
  37. #open our i/o files
  38. outf = open(out_file,'w')
  39. outf_failed = open(out_file_failed,'w')
  40. inf = open(addr_file,'r')
  41. for address in inf:
  42. #get latitude and longitude of address
  43. data = geocode(address)
  44. #output results and log to file
  45. if len(data)>1:
  46. print "Latitude and Longitude of "+address+":"
  47. print "\tLatitude:",data['lat']
  48. print "\tLongitude:",data['lng']
  49. outf.write(address.strip()+data['lat']+','+data['lng']+'\n')
  50. outf.flush()
  51. else:
  52. print "Geocoding of '"+addr+"' failed with error code "+data['code']
  53. outf_failed.write(address)
  54. outf_failed.flush()
  55. #play nice and don't just pound the server with requests
  56. time.sleep(sleep_time)
  57. #clean up
  58. inf.close()
  59. outf.close()
  60. outf_failed.close()
  61. if __name__ == "__main__":
  62. main()

Report this snippet  

You need to login to post a comment.