Source

hokiefinder / geolocator / google_geocoding.py

Full commit
import urllib
import urllib2
import StringIO
import gzip
import json

ZERO_RESULTS = 'ZERO_RESULTS'
OVER_QUERY_LIMIT = 'OVER_QUERY_LIMIT'
REQUEST_DENIED = 'REQUEST_DENIED'
INVALID_REQUEST = 'INVALID_REQUEST'  

def get_location(address):
	address = urllib.quote_plus(address)
	sensor = 'false'
	request_str = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=%s' % (address, sensor)
	request = urllib2.Request(request_str)
	request.add_header('Accept-Encoding', 'gzip')
	response = urllib2.urlopen(request)
	compressed = response.info().getheader('Content-Encoding') == 'gzip'
	jsonString = response.read()
	if compressed:
		compressed_stream = StringIO.StringIO(json)
		gzip_stream = gzip.GzipFile(fileobj = compressed_stream)
		jsonString = gzip_stream.read()
	jsonData = json.loads(jsonString)
	status = jsonData['status']
	if status == ZERO_RESULTS:
		raise Warning('Zero Results')
	elif status == OVER_QUERY_LIMIT:
		raise Warning('Over Query Limit')
	elif status == REQUEST_DENIED:
		raise Warning('Request Denied')
	elif status == INVALID_REQUEST:
		raise Warning('Invalid Request')
	if len(jsonData['results']) > 0:
		result = jsonData['results'][0]
		try:
			addr = result['formatted_address']
			lat = result['geometry']['location']['lat']
			lng = result['geometry']['location']['lng']
		except KeyError:
			raise Warning('No Location Provided')
			return (None, None, None)
		else:
			return (addr, lat, lng)