0

I was wondering if you could please help me with an issue I am having with the google distance matrix api.

Please see my code below:

////////////////////////////////////////////////////////////////
    var build = function (pc) {
        var origin = "london";
        var dest = pc;
        var service = new google.maps.DistanceMatrixService();
        service.getDistanceMatrix(
                {
                    origins: [origin],
                    destinations: [dest],
                    travelMode: google.maps.TravelMode.DRIVING,
                    durationInTraffic: true,
                    avoidHighways: false,
                    unitSystem: google.maps.UnitSystem.METRIC,
                    avoidTolls: false
                }, callback);
        function callback(response, status) {
           var distanceVal = response.rows[0].elements[0].distance.value;
           return distanceVal;
        }
    };
////////////////////////////////////////////////////////////////
    for (var i = 0; i < dealers.length; i++) {
        var postcode = dealers[i].address[0].postcode;
        var output = build(postcode);
        console.log(output);
    }   
///////////////////////////////////////////////////////////////////////////

When it writes to the console I would like to see the different values that are returned from the google api. For some reason it doesn't seem to return anything

Thanks in advance

KM123
  • 1,339
  • 1
  • 10
  • 21
  • The distance service is asynchronous, you need to use the returned data in the callback function when it is available. – geocodezip Dec 03 '14 at 14:48

1 Answers1

0

Put the console.log code inside the callback function before the return ...

rfornal
  • 5,072
  • 5
  • 30
  • 42
  • Hi thanks for your answer. Unfortunately this wouldn't work for what I require. I need to access variables and use the data within the for loop – KM123 Dec 03 '14 at 14:50
  • There are variables that cannot be accessed while inside the function? From what I can see, if dealers can be accessed while in the callback function you should be OK. – rfornal Dec 03 '14 at 14:53