I'm having a hard time with the script. This is what it should do:
When the Geocode and submit 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:
http://jsfiddle.net/spadez/XyCF9/1/
$(function () {
var lastQuery = null,
lastResult = null, // new!
autocomplete,
processLocation = function (input, lat, long, 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) {
if (callback) {
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!
}
if (callback) {
callback(lastResult); // send the result back
}
});
},
ctryiso = $("#ctry").val(),
options = {
types: ["geocode"]
};
if (ctryiso !== '') {
options.componentRestrictions= { 'country': ctryiso };
}
autocomplete = new google.maps.places.Autocomplete($("#loc")[0], options);
google.maps.event.addListener(autocomplete, 'place_changed', processLocation);
$('#search').click(function (e) {
var form = $(this).closest('form'),
input = $("#loc"),
lat = $("#lat"),
lng = $("#lng");
e.preventDefault(); // stop the submission
processLocation(input, lat, lng, function (success) {
if (success) { // if the geocoding succeeded, submit the form
form.submit();
}
});
});
$('#geosearch').click(function (e) {
var form = $(this).closest('form'),
input = $("#geoloc"),
lat = $("#geolat"),
lng = $("#geolng");
e.preventDefault(); // stop the submission
processLocation(input, lat, lng);
});
});
The error I'm getting at the moment is:
- Uncaught TypeError: Cannot call method 'val' of undefined fiddle.jshell.net/:39
- Uncaught TypeError: Object # has no method 'val' fiddle.jshell.net/:56
Can anyone shed some light on where I am going wrong with this please?