Skip to content

Instantly share code, notes, and snippets.

@edsu
Last active December 14, 2015 06:39
Show Gist options
  • Save edsu/5044859 to your computer and use it in GitHub Desktop.
Save edsu/5044859 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import json
import urllib
def geocode(postal_code):
"""A function for turning a postal code into a geo-coordinate using Freebase."""
url = "https://www.googleapis.com/freebase/v1/mqlread?query="
q = {
"type": "/location/postal_code",
"/location/postal_code/postal_code": postal_code,
"/location/location/geolocation": {
"/location/geocode/latitude": None,
"/location/geocode/longitude": None
}
}
r = json.loads(urllib.urlopen(url + urllib.quote(json.dumps(q))).read())
if not r['result']:
return None
geo = r['result']['/location/location/geolocation']
return geo['/location/geocode/latitude'], geo['/location/geocode/longitude']
# but not all postal codes are in freebase, try BN1 9QR
for postal_code in ["20901", "BN1 9RH"]:
print postal_code, ": ", geocode(postal_code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment