I am writing a website using Python / Django, and am currently doing server-side geocoding through the geopy module. I would like to implement a progressive enhancement of doing the geocoding via Javascript (to make sure I don’t hit Google’s daily limit of geocode requests / user), and then pass the results of the Javascript geocoding to the server for further processing.
What I am currently doing is using javascript and the Google geocoding API to get the (lat, lon) coordinates and add them as hidden inputs into my form. However, I am not sure how to submit this form with the (lat, lon) without running into an infinite loop. I would rather stay away from sending this via Ajax because for this particular page 99.9% of the page needs to be refreshed, and I would like to keep the design as simple as possible, so Ajax would be overkill.
I played around with putting the event.preventDefault() into an if statement testing for existence of the hidden lat/lon variables, but could not get it to work.
Any ideas? Thanks in advance! Vasiliy
$(document).ready(function() {
var g = new GoogleGeocode();
//bind event handler
$('#address_form').bind('submit', function(event){
//get address from form
var address = $('#id_address').val();
event.preventDefault();
//get lat/lon
g.geocode(address, function(data) {
if(data != null) {
alert(data.longitude + " " + data.latitude);
//insert lat and lon into the form
$('<input type="hidden" id="lat" name="lat" value="' + data.latitude + '"/>').appendTo('form');
$('<input type="hidden" id="lon" name="lon" value="' + data.longitude + '"/>').appendTo('form');
} else {
alert('ERROR! Unable to geocode address');
}
});
});
});
You should
unbindthe formsubmitevent handler once you are sure you have to submit the form. Try this});