Created
December 23, 2013 12:37
-
-
Save taylanpince/8096410 to your computer and use it in GitHub Desktop.
Address geocoding with geopy
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 simplejson as json | |
from geopy.geocoders.googlev3 import GoogleV3 | |
from urllib import urlopen | |
from django.conf import settings | |
from django.contrib.gis.geos import GEOSGeometry | |
from django.db.models import signals | |
from specials.models import Special | |
GEONAMES_TIMEZONE_API = "http://ws.geonames.org/timezoneJSON?lat=%(latitude)f&lng=%(longitude)f" | |
def geolocate_store(sender, instance, created, **kwargs): | |
""" | |
Generate and save the coordinates for a store | |
""" | |
if not instance.coordinates and instance.address: | |
geocoder = GoogleV3() | |
try: | |
results = geocoder.geocode(u"%(address)s, %(postal_code)s" % { | |
"address": instance.address.encode("ascii", "replace"), | |
"postal_code": instance.postal_code.encode("ascii", "replace"), | |
}) | |
address, coordinates = results | |
except: | |
coordinates = None | |
if coordinates: | |
try: | |
timezone = json.load(urlopen(GEONAMES_TIMEZONE_API % { | |
"latitude": coordinates[0], | |
"longitude": coordinates[1], | |
})).get("timezoneId", None) | |
except KeyError: | |
timezone = None | |
instance.coordinates = GEOSGeometry("POINT(%f %f)" % (coordinates[1], coordinates[0])) | |
if timezone: | |
instance.timezone = timezone | |
instance.save() | |
def geolocate_city(sender, instance, created, **kwargs): | |
""" | |
Generate and save the coordinates for a city | |
""" | |
if not instance.coordinates: | |
geocoder = geocoders.Google(api_key=settings.GOOGLE_MAPS_SERVER_API_KEY) | |
try: | |
results = list(geocoder.geocode(u"%(city)s" % { | |
"city": instance.name.encode("ascii", "replace"), | |
}, exactly_one=False)) | |
address, coordinates = results[0] | |
except: | |
coordinates = None | |
if coordinates: | |
instance.coordinates = GEOSGeometry("POINT(%f %f)" % (coordinates[1], coordinates[0])) | |
instance.save() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment