public
Last active

Django (1.3) Google Maps v3 Geocoder service lookup example

  • Download Gist
helpers.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
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 ''
models.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
# ...
 
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
 
# ...

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.