I have a simple javascript function that checks whether the user has input values in the City and State input elements, and if they did, geocodes the city and state and then sets two other inputs in the form (lat and long) and should return true if it succeeded or false if otherwise. The problem I am running into is that when it calls the geocoder.geocode, javascript just skips over it and hits the bottom. I know that javascript is asynchronous so it's calling the geocode, then keeps going but hits the end of the function so it just returns nothing instead of returning something from the geocode call. This function is being used by an "onsubmit" for a form so I need it to return true when everything works properly but false when it doesn't to stop the form from being submitted. How do you write a function in javascript that returns a boolean but has to call another function?
function geocodeVerification()
{
if($("#userCity").val() && $("#userState").val())
{
var geocodeLocation = $("#userCity").val() + "," + $("#userState").val();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address':geocodeLocation},function(results,status)
{
if(status == google.maps.GeocoderStatus.OK)
{
console.log("Entered OK status");
$("#locationLat").val(results[0].geometry.location.lat());
$("#locationLong").val(results[0].geometry.location.lng());
console.log("Setting Lat and Long");
console.log("Lat: "+ results[0].geometry.location.lat());
console.log("Long: "+ results[0].geometry.location.lng());
return true;
}
else if(status == google.maps.GeocoderStatus.INVALID_REQUEST)
{
console.log("Entered INVALID_REQUEST status");
alert("An invalid request was sent. Please check the city/state for errors");
return false;
}
else if(status == google.maps.GeocoderStatus.ERROR)
{
console.log("Entered ERROR status");
alert("There was a problem contacting the Google Servers");
return false;
}
else if(status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT)
{
console.log("Entered OVER_QUERY_LIMIT status");
alert("The query limit has been reached. Please wait a minute and try again.");
return false;
}
else if(status == google.maps.GeocoderStatus.REQUEST_DENIED)
{
console.log("Entered REQUEST_DENIED status");
alert("Request was denied. This webpage is not allowed to use the geocoder");
return false;
}
else if(status == google.maps.GeocoderStatus.UNKNOWN_ERROR)
{
console.log("Entered UNKNOWN_ERROR status");
alert("A geocoding request could not be processed due to a server error. The request may succeed if you try again");
return false;
}
else if(status == google.maps.GeocoderStatus.ZERO_RESULTS)
{
console.log("Entered ZERO_RESULTS status");
alert("Geocoding " + geocodeLocation +" has returned no results, please check for errors and try again.");
return false;
}
else
{
console.log("defaulted out");
return false;
}
});
}
else
{
alert("City and/or State values are incorrect");
return false;
}
}