I’m new to JavaScript. I have been trying to design some code which geocodes a location when a search button is hit and the submits the form if successful. To make it to slightly more complicated, if an option from the autosuggest is selected, it also geocodes it even before the search button is hit.
This all seems to work, except that the form is never submitted and I can’t figure out why.
Link: http://jsfiddle.net/sR4GR/42/
$(function () { var input = $("#loc"), lat = $("#lat"), lng = $("#lng"), lastQuery = null, lastResult = null, // new! autocomplete; function processLocation(query, callback) { // accept a callback argument var query = $.trim(input.val()), geocoder; // if query is empty or the same as last time... if( !query || query == lastQuery ) { callback(lastResult); // send the same result as before return; // and stop here } lastQuery = query; // store for next time geocoder = new google.maps.Geocoder(); geocoder.geocode({ address: query }, function(results, status) { if( status === google.maps.GeocoderStatus.OK ) { lat.val(results[0].geometry.location.lat()); lng.val(results[0].geometry.location.lng()); lastResult = true; // success! } else { alert("Sorry - We couldn't find this location. Please try an alternative"); lastResult = false; // failure! } callback(lastResult); // send the result back }); } autocomplete = new google.maps.places.Autocomplete(input[0], { types: ["geocode"], componentRestrictions: { country: "uk" } }); google.maps.event.addListener(autocomplete, 'place_changed', processLocation); $('#searchform').on('submit', function (event) { var form = this; event.preventDefault(); // stop the submission processLocation(function (success) { if( success ) { // if the geocoding succeeded, submit the form form.submit() } }); }); });
Advertisement
Answer
You’re calling:
processLocation(function (success) {
But your processLocation has the callback on the second parameter:
function processLocation(query, callback)
Try removing the query parameter from processLocation:
function processLocation(callback)
OR call it with a blank argument:
processLocation(null, function (success)