Save Geolocation for an Address based model on save()

 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 6 years, 9 months ago
  2. Save a model using an arbitrary db connection by weswinham 4 years, 7 months ago
  3. Models for Postal Addresses by MasonM 5 years, 8 months ago
  4. BigIntegerField and BigAutoField by fnl 5 years, 4 months ago
  5. Another means of updating a subset of a model's fields by insin 6 years, 4 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)

#

(Forgotten your password?)