Geocoding an address on form submission?
You can override the model's save method. I geocode the data before saving. This is using googleapi, but it can be modified accordingly.
import urllib
def save(self):
location = "%s, %s, %s, %s" % (self.address, self.city, self.state, self.zip)
if not self.latitude or not self.longitude:
latlng = self.geocode(location)
latlng = latlng.split(',')
self.latitude = latlng[0]
self.longitude = latlng[1]
super(Marker, self).save()
def geocode(self, location):
output = "csv"
location = urllib.quote_plus(location)
request = "http://maps.google.com/maps/geo?q=%s&output=%s&key=%s" % (location, output, settings.GOOGLE_API_KEY)
data = urllib.urlopen(request).read()
dlist = data.split(',')
if dlist[0] == '200':
return "%s,%s" % (dlist[2], dlist[3])
else:
return ','
Update for Google Maps API v3:
import json
import urllib.parse
from decimal import Decimal
def save(self):
if not self.lat or not self.lng:
self.lat, self.lng = self.geocode(self.address)
super(Location, self).save()
def geocode(self, address):
address = urllib.parse.quote_plus(address)
maps_api_url = "?".join([
"http://maps.googleapis.com/maps/api/geocode/json",
urllib.parse.urlencode({"address": address, "sensor": False})
])
response = urllib.urlopen(maps_api_url)
data = json.loads(response.read().decode('utf8'))
if data['status'] == 'OK':
lat = data['results'][0]['geometry']['location']['lat']
lng = data['results'][0]['geometry']['location']['lng']
return Decimal(lat), Decimal(lng)
You could also use the django.db.models.signals.pre_save
-signal!
Have a look at Django's signal documentation at http://docs.djangoproject.com/en/dev/topics/signals/.