- 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
- find even number by Rajeev529 2 weeks, 3 days ago
- Form field with fixed value by roam 1 month, 1 week ago
- New Snippet! by Antoliny0919 1 month, 2 weeks ago
- Add Toggle Switch Widget to Django Forms by OgliariNatan 4 months ago
- get_object_or_none by azwdevops 7 months, 3 weeks ago
Comments
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.