Skip to content

Instantly share code, notes, and snippets.

@hiway
Last active December 18, 2015 19:39
Show Gist options
  • Save hiway/5834566 to your computer and use it in GitHub Desktop.
Save hiway/5834566 to your computer and use it in GitHub Desktop.
Helper module to get latitude, longitude of addresses using Google Maps API.
import re
import requests
def _clean_degrees(value):
return re.sub('[^-\.0-9]', '', value)
def get_coordinates(address):
"""Expects a string of address and returns tuple
(latitude, longitude)
Uses Google's APIs (not intended for this use) for geocoding
addresses. Don't abuse their generosity :)"""
endpoint = 'http://maps.google.com?q=%s&output=js' % address
r = requests.get(endpoint)
if r.status_code is not 200:
raise Exception('Server returned status code: %s' % r.status_code)
data = r.text
if '<error>' in data:
raise Exception('Unable to geocode: %s' % address)
else:
# find the bit where map's center is supposed to point
x = data.find('{center')+9
y = data.find('}', x)
center = data[x:y]
# remove cruft
center = center.replace('lat:', '')
center = center.replace('lng:', '')
# we have just the latitude and longitude left now
lat, lng = center.split(',')
return (_clean_degrees(lat), _clean_degrees(lng))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment