Created
August 29, 2013 15:31
-
-
Save nicksnell/6379600 to your computer and use it in GitHub Desktop.
Quick & dirty utility to geocode an address into lat/lng
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import urllib | |
| import urllib2 | |
| import json | |
| def geocode(address): | |
| """Quick & Dirty utility to get geocoded lat/lng from Google Geocode API""" | |
| address = urllib.quote(address.replace(' ', '+').encode('utf-8')) | |
| query = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false' % address | |
| raw_json = None | |
| try: | |
| response = urllib2.urlopen(query) | |
| raw_json = response.read() | |
| except urllib2.HTTPError, e: | |
| return None | |
| except urllib2.URLError, e: | |
| return None | |
| if not raw_json: | |
| return None | |
| try: | |
| json_response = json.loads(raw_json) | |
| lat = json_response['results'][0]['geometry']['location']['lat'] | |
| lng = json_response['results'][0]['geometry']['location']['lng'] | |
| except Exception: | |
| return None | |
| return lat, lng | |
| if __name__ == '__main__': | |
| print geocode('Cromwell Rd, London SW7 5BD, UK') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment