Login

Save Geolocation for an Address based model on save()

Author:
publicFunction
Posted:
July 22, 2013
Language:
Python
Version:
1.4
Score:
0 (after 0 ratings)

This code will work on any model using correct address data in its fields that also require latitude and longitude data to be updated on saving.

It uses pythons own default urllib and json, so no need to install 3rd party stuff to make it work.

This method is preferred to getting it on the fly, due to the OVER_QUERY_LIMIT that you will get when parsing many address, this way means it stays up to day in the model and will update when any part of the address changes.

 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
* models.py *

import json, urllib

def getLatLon(address):
    address = urllib.quote_plus(address)
    geo = urllib.urlopen("http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=%s" % (address))
    return geo.read()

class location(models.Model):
    ...
    address_1 = models.CharField(max_length=200)
    address_2 = models.CharField(max_length=200, blank=True, null=True)
    address_3 = models.CharField(max_length=200, blank=True, null=True)
    city = models.CharField(max_length=200)
    postcode = models.CharField(max_length=15)
    ...
    latitude = models.FloatField(null=True, blank=True)
    longitude = models.FloatField(null=True, blank=True)
    ...
    
    def save(self, *args, **kwargs):
        geo = json.loads(getLatLon("%s,%s,%s,%s %s" % (self.address_1, self.address_2, self.address_3, self.city, self.postcode)))
        if geo['status'] == "OK":
            self.latitude = geo['results'][0]['geometry']['location']['lat']
            self.longitude = geo['results'][0]['geometry']['location']['lng']
        super(directory_list, self).save(*args, **kwargs)

More like this

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

Comments

jmfrouin (on August 8, 2013):

To be fully functionnal, you have to change the line 27 from :

super(directory_list, self).save(args, *kwargs)

to

super(location, self).save(args, *kwargs)

#

Please login first before commenting.