Skip to content

Instantly share code, notes, and snippets.

@mhulse
Created June 15, 2011 19:34
Show Gist options
  • Save mhulse/1027898 to your computer and use it in GitHub Desktop.
Save mhulse/1027898 to your computer and use it in GitHub Desktop.
Django (1.3) Google Maps v3 Geocoder service lookup example
import urllib, urllib2, simplejson
from django.utils.encoding import smart_str
def get_lat_lng(location):
# http://djangosnippets.org/snippets/293/
# http://code.google.com/p/gmaps-samples/source/browse/trunk/geocoder/python/SimpleParser.py?r=2476
# http://stackoverflow.com/questions/2846321/best-and-simple-way-to-handle-json-in-django
# http://djangosnippets.org/snippets/2399/
location = urllib.quote_plus(smart_str(location))
url = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false' % location
response = urllib2.urlopen(url).read()
result = simplejson.loads(response)
if result['status'] == 'OK':
lat = str(result['results'][0]['geometry']['location']['lat'])
lng = str(result['results'][0]['geometry']['location']['lng'])
return '%s,%s' % (lat, lng)
else:
return ''
# ...
from app.helpers import get_lat_lng
# ...
class Place(models.Model):
title = models.CharField(_(u'title'), max_length=255)
address1 = models.CharField(_(u'address'), max_length=255, blank=True)
address2 = models.CharField(_(u'address (cont.)'), max_length=255, blank=True)
city = models.CharField(_(u'city'), max_length=255, blank=True)
state = USStateField(_(u'state'), blank=True)
zip = models.CharField(_(u'ZIP'), max_length=10, blank=True)
country = models.CharField(_(u'country'), blank=True, max_length=100)
latlng = models.CharField(_(u'Latitude/Longitude'), blank=True, max_length=100, help_text=_(u'Note: This field will be filled-in automatically based on the other address bits.'))
phone = PhoneNumberField(_(u'phone'), blank=True)
email = models.EmailField(_(u'e-mail'), blank=True)
website = models.URLField(_(u'website'), blank=True)
about = models.TextField(_(u'about'), blank=True)
class Meta:
abstract = True
def save(self, *args, **kwargs):
# If latlng has no value:
if not self.latlng:
# Add + between fields with values:
location = '+'.join(filter(None, (self.address1, self.address2, self.city, self.state, self.zip, self.country)))
# Attempt to get latitude/longitude from Google Geocoder service v.3:
self.latlng = get_lat_lng(location)
super(Place, self).save(*args, **kwargs)
class Stadium(Place):
slug = models.SlugField(_(u'slug'), max_length=255, unique=True)
class Meta:
pass
@models.permalink
def get_absolute_url(self):
return('stadium_detail', (), { 'slug': self.slug })
def __unicode__(self):
return u'%s' % self.title
# ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment