Skip to content

Instantly share code, notes, and snippets.

@craigds
Created February 24, 2011 23:53
Show Gist options
  • Save craigds/843161 to your computer and use it in GitHub Desktop.
Save craigds/843161 to your computer and use it in GitHub Desktop.
Gets search results from Google Maps for the given string
#!/usr/bin/env python
"""
Gets search results from Google Maps for the given string.
Usage:
mapsearch.py "address" [region]
Regions are two-character ccTLDs: http://en.wikipedia.org/wiki/CcTLD
They're not validated by this script
"""
import sys
import urllib
try:
import json
except:
import simplejson as json
GMAPS_URL = 'http://maps.googleapis.com/maps/api/geocode/json?'
def gmaps_address_search(s, region=None):
query = {
'address': s,
'sensor': 'false',
}
if region:
query['region'] = region
url = GMAPS_URL + urllib.urlencode(query)
print >>sys.stderr, url
response = urllib.urlopen(url)
if response.code != 200:
raise RuntimeError("Server returned bad response (%d):\n%s" % (response.code, response.read()))
data = json.loads(response.read())
return data['results']
def main():
s = sys.argv[1]
region = None
if len(sys.argv) > 2:
region = sys.argv[2]
for result in gmaps_address_search(s, region=region):
latlng = result['geometry']['location']
latlng = latlng['lat'], latlng['lng']
print '%s:\n\t%4f, %4f\n' % (result['formatted_address'], latlng[1], latlng[0])
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment