Login

Google Geocode Lookup

Author:
tonyskyday
Posted:
June 22, 2007
Language:
Python
Version:
.96
Score:
11 (after 11 ratings)

Makes a call to Google's geocoder and returns the latitude and longitude as a string or returns an empty string. Called by the save method to save the lat and long to the db to be used when rendering maps on the frontend. Reduces the number of calls to geocoder by calling only when saving, not on every viewing of the object.

Be sure to import urllib and the project's settings, and to define GOOGLE_API_KEY in settings.py.

Example:

def save(self):
    location = "%s+%s+%s+%s" % (self.address, self.city, self.state, self.zip_code)
    self.lat_long = get_lat_long(location)
    if not self.lat_long:
        location = "%s+%s+%s" % (self.city, self.state, self.zip_code)
        self.lat_long = get_lat_long(location)

    super(Foo, self).save()
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#
# models.py
#
import urllib
import settings

def get_lat_long(location):
    key = settings.GOOGLE_API_KEY
    output = "csv"
    location = urllib.quote_plus(location)
    request = "http://maps.google.com/maps/geo?q=%s&output=%s&key=%s" % (location, output, key)
    data = urllib.urlopen(request).read()
    dlist = data.split(',')
    if dlist[0] == '200':
        return "%s, %s" % (dlist[2], dlist[3])
    else:
        return ''

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

falsh (on October 30, 2009):

get problems with : location = urllib.quote_plus(location)

when location has some accents

#

falsh (on October 30, 2009):

solution : location = smart_str(urllib.quote_plus(location))

#

anentropic (on November 22, 2009):

does this return "lat, lon" or "lon, lat" ?

#

anentropic (on November 22, 2009):

P.S. great snippet, thanks

#

anentropic (on February 6, 2010):

@falsh ...you mean:

location = urllib.quote_plus(smart_str(location))

(the other way still throws errors if you have foreign chars)

#

Please login first before commenting.