Login

Save Geolocation for an Address based model on save()

Author:
publicFunction
Posted:
July 22, 2013
Language:
Python
Version:
1.4
Tags:
Geolocation Geolocation on save Google Geolocation
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. MaxMind(R) GeoIP Lite geolocation models by jbronn 7 years, 11 months ago
  2. Save a model using an arbitrary db connection by weswinham 5 years, 10 months ago
  3. Models for Postal Addresses by MasonM 6 years, 11 months ago
  4. BigIntegerField and BigAutoField by fnl 6 years, 6 months ago
  5. Another means of updating a subset of a model's fields by insin 7 years, 7 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.