I am using Google Maps API to get the distance between 2 UK postcodes.
var yourPostcode = $("#YourPostcode").val();
var restaurantPostcode = $("#Postcode").val();
var point1 = GetPointFromPostcode(yourPostcode);
var point2 = GetPointFromPostcode(restaurantPostcode);
var distance = point1.distanceFrom(point2, 3959).toFixed(1);
However the GetPoint function calls Google API Asynchronously and so by the time distance is calculated point1 and 2 have not been set (I believe this is what is happening?)
I also put alerts after each statement to check the value of the variables and doing this I got distance to be the correct value, waiting for me to click ok must have given it enough time to get the results? Though it does not do this anymore :(
Here is the get point function
function GetPointFromPostcode(postcode) {
var point;
localSearch.execute(postcode + ", UK");
if (localSearch.results[0]) {
var resultLat = localSearch.results[0].lat;
var resultLng = localSearch.results[0].lng;
point = new GLatLng(resultLat, resultLng);
} else {
$(".PostcodeError").append("Postcode Invalid");
}
return point;
}
I know I can set a callback on local search for to be called when the results come back but the problem here is there are 2 searches.
What I want is to only call the calculate distance line after BOTH searches have returned results.
Do you know how I could do this?
Thanks