views:

539

answers:

2

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

+4  A: 

If you are able to get GPS coordinates (latitude, longitude) for each postal code, build a Javascript distance function.

Find it here in C#, but the concept is the same if you want to reproduce this in JS.

Chris Ballance
A: 

This might work - essentially turning the setSearchCompleteCallback to react differently depending on whether it's searching the first or second postcode.

var searchControl= new google.search.SearchControl();
var distanceSearch = new google.search.LocalSearch();
searchControl.addSearcher(distanceSearch);

distanceSearch.setSearchCompleteCallback(null, function() {
    if(distanceSearch.results.length > 0 && distanceSearch.postcode2)
    {
       distanceSearch.point1 = new GLatLng(distanceSearch.results[0].lat, distanceSearch.results[0].lng)
       var postcode2 = distanceSearch.postcode2;
       distanceSearch.postcode2 = null;    
       distanceSearch.execute(postcode2 + ", UK");
    } else if (distanceSearch.results.length > 0 && !distanceSearch.postcode2) {
       distanceSearch.point2 = new GLatLng(distanceSearch.results[0].lat, distanceSearch.results[0].lng)
       //some code to calculate distance and write it to somewhere
    } else {
       //no search results
    }
});

function measureDistance(postcode1, postcode2) { 
    distanceSearch.postcode2 = postcode2;
    distanceSearch.execute(postcode1 + ", UK");
}
wheresrhys