I'm pretty excited to have coded my first JavaScript file which now works, and I've spent my evening trying to improve it.
It takes a location in the #loc input box and geocodes it (gets coordinates from a location) when the search button is pressed, or when the autosuggestion is clicked, then submits the form.
I've worked hard on this but I am really interested to see if any JavaScript gurus can spot any mistakes, because I love beautiful code.
var coded = false; geocode(); $.cookie("country", "uk"); // GEOCODE FUNCTION function geocode() { var input = $('#loc')[0]; var options = {types: ['geocode']}; var country_code = $.cookie('country'); 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(); }); $('#searchform').on('submit', function(e) { if (coded === false) { processLocation(); } return true; }); $("#loc").bind("change paste keyup", function() { coded = false; }); } function processLocation() { var geocoder = new google.maps.Geocoder(); var address = $('#loc').val(); geocoder.geocode({ 'address': address }, function(results, status) { if (status === google.maps.GeocoderStatus.OK) { coded = true; $('#lat').val(results[0].geometry.location.lat()); $('#lng').val(results[0].geometry.location.lng()); } else { coded = false; alert("Sorry - We couldn't find this location. Please try an alternative"); } }); coded = true; }