I have a problem where I have some code which I want to apply to two slightly different applications, but 75% of the code will be the same. This is where I am with things:
http://jsfiddle.net/spadez/H6SZ2/6/
$(function () {
var input = $("#loc"),
lat = $("#lat"),
lng = $("#lng"),
lastQuery = null,
lastResult = null, // new!
autocomplete;
function processLocation(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
});
}
var ctryiso = $("#ctry").val();
var options = {
types: ["geocode"]
};
if(ctryiso != ''){
options.componentRestrictions= { 'country': ctryiso };
}
autocomplete = new google.maps.places.Autocomplete(input[0], options);
google.maps.event.addListener(autocomplete, 'place_changed', processLocation);
$('#search_form').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()
}
});
});
});
When the submit form button is pressed it will do the following (this works already):
- Check if result is already geocoded from autosuggest click
- If not, geocode
- Submit the form if successful
When the Geocode button is pressed I want it to do the following (this doesn't work):
- Check if result is already geocoded from autosuggest click
- If not, geocode
So my question is, how can I make it so I can use the same code for both scripts without having to duplicate it twice. My idea was to do the following:
- Have a function for the "submit form" button which includes submitting the form
- Have a function for the geocode button which does not include submitting the form
I would rather use a function for each button rather than using some kind of flag, but I am completely stuck on how to implement this, every time I work on it I end up breaking the script completely. I am new to JavaScript.