Reputation: 183
I have a form in which an address will be entered and I want to store the associated coordinates in my database. When I have a separate button for the geocoding, it operates fine in terms of updating the hidden values in my form. I then click a separate submit button the values are stored as I want them.
What I really want though is to click on one button which retrieves the coordinates and submits the form once these values have been retrieved and the code I have below does not seem to be accomplishing this.
<script type="text/javascript">
var geocoder;
geocoder = new google.maps.Geocoder();
function codeAddress() {
var address = document.getElementById("place_name").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById("place_coordinates").value = results[0].geometry.location;
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
// document.forms["new_place"].submit();
}
</script>
<!-- the form -->
<input type="button" value="Submit" onclick="codeAddress()">
At present the form is submitting but without the "place_coordinates" hidden values being submitting with the form. Help is much appreciated
Upvotes: 0
Views: 398
Reputation: 150040
If you cancel the default form submission and then submit it yourself from the callback function of the geocode call it should do the trick.
Rather than handling the click of the button, handle the submit event of the form, making sure to return false to cancel default submission (in this case I'm returning the result of the function, so make sure the function returns false):
<form onsubmit="return codeAddress(this);">
<script>
var geocoder;
geocoder = new google.maps.Geocoder();
function codeAddress(theForm) {
var address = document.getElementById("place_name").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById("place_coordinates").value = results[0].geometry.location;
theForm.submit();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
return false;
}
</script>
Note that I've put the form submission in the OK branch of your if/else, so the form will not be submitted if the geocode was unsuccessful. Obviously you can move that to after the else case but still in the callback function if you want to go ahead and submit either way.
Also, notice I'm passing a reference to the form into the function - you don't have to do this, but I think it's neater.
Upvotes: 1