I am new to javascript but I am having a hard time creating code which can achieve this logic:
I am trying to achieve the following logic:
If a user enters text in location box and DOES click autosuggestion Then geocode and set coded flag to "True"
If a user enters text in location DOES NOT click autosuggestion Keep coded flag to "False"
If a user changes the text in location box Make sure "coded" flag is set to "false" - Since the text doesnt match the coordinates we fetched for it now
If a user clicks search button Check "coded" flag If true, submit form If false, process geocode, and if successful, submit form
This is how far I got before I got stuck: LINK
Even when I click on an autosuggested link, which initiates a geocode, and then do not change the content in the input box, when I hit search it says "Location not geocoded - Process location first". I feel like my logic in the programming is wrong but I am not sure how to fix it without lots of ugly repetitive code.
FULL CODE
geocode();
// SET COOKIE FOR TESTING PURPOSES
$.cookie("country", "uk");
// GEOCODE FUNCTION
function geocode() {
var coded = false;
console.log(coded);
var input = document.getElementById('loc');
var options = {
types: ['geocode']
};
var country_code = $.cookie('country');
console.log(country_code);
if (country_code) {
options.componentRestrictions = {
'country': country_code
};
}
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
processLocation();
});
// ON SUBMIT - WORK OUT IF WE ALREADY HAVE THE RESULTS FROM AUTOCOMPLETE FUNCTION
$('#searchform').on('submit', function(e) {
console.log(coded);
e.preventDefault();
if(coded == true) {
console.log("Location already geocoded - Submitting form");
$('#searchform').submit();
}
else {
console.log("Location not geocoded - Process location first");
processLocation();
}
});
// CHECK TO SEE IF INPUT HAS CHANGED SINCE BEING GEOCODED
// IF "CODED" VAR IS FALSE THEN WE WILL GEOCODE WHEN SEARCH BUTTON HIT
$("#loc").bind("change paste keyup", function() {
var coded = false;
console.log("Content changed - Coordinates no longer valid");
});
};
// GEOCODE THE LOCATION
function processLocation(){
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('loc').value;
geocoder.geocode({
'address': address
},
// RESULTS - STORE COORDINATES IN FIELDS OR ERROR IF NOT SUCCESSFUL
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var coded = true;
console.log("Geocode Successful");
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
} else {
var coded = false;
console.log("Geocode unsuccessful");
alert("Sorry - We couldn't find this location. Please try an alternative")
}
});
}