nifCody
nifCody

Reputation: 2444

Google Distance Matrix need to return the value

I have using google distance matrix api to getting the shortest distance of two geo points from the following way:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>

    var origin1 = new google.maps.LatLng(9.6667, 80.0000);
    var destinationA = new google.maps.LatLng(9.6689, 80.0059);



    function calculateDistances() {


        var service = new google.maps.DistanceMatrixService();
        service.getDistanceMatrix(
            {
                origins: [origin1],
                destinations: [destinationA],
                travelMode: google.maps.TravelMode.DRIVING,
                unitSystem: google.maps.UnitSystem.METRIC,
                avoidHighways: false,
                avoidTolls: false
            }, callback);

    }

    function callback(response, status) {
        if (status != google.maps.DistanceMatrixStatus.OK) {
            alert('Error was: ' + status);
        } else {
            var origins = response.originAddresses;


            for (var i = 0; i < origins.length; i++) {
                var results = response.rows[i].elements;
                for (var j = 0; j < results.length; j++) {
                    alert(results[j].distance.text);
                }
            }
        }
    }


</script>

On this code I have get the shortest distance successfully. But I need to return the value when calling the method calculateDistances() instead of alert the value. How can i do in callback methods!.

Upvotes: 1

Views: 3978

Answers (2)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59338

Distance Matrix service is asynchronous, for that reason, you need to pass a callback method to execute upon completion of the request, to process the results. But you could consider to convert async API to promises.

The following example demonstrates how to convert Distance Matrix service API to promises using jQuery:

var origin1 = new google.maps.LatLng(9.6667, 80.0000);
var destinationA = new google.maps.LatLng(9.6689, 80.0059);



function calculateDistances(origins,destinations) {
            var service = new google.maps.DistanceMatrixService();
            var d = $.Deferred();
            service.getDistanceMatrix(
                {
                    origins: origins,
                    destinations: destinations,
                    travelMode: google.maps.TravelMode.DRIVING,
                    unitSystem: google.maps.UnitSystem.METRIC,
                    avoidHighways: false,
                    avoidTolls: false
                }, 
                function(response, status){
                  if (status != google.maps.DistanceMatrixStatus.OK) {
                     d.reject(status);
                  } else {
                     d.resolve(response);
                  }
                });
            return d.promise();
}

        


        calculateDistances([origin1],[destinationA])
           .done(function(response){

                var origins = response.originAddresses;

                for (var i = 0; i < origins.length; i++) {
                    var results = response.rows[i].elements;
                    for (var j = 0; j < results.length; j++) {
                        //console.log(results[j].distance.text);
                        document.getElementById('result').innerHTML += results[j].distance.text;
                    }
                }

           })
           .fail(function(status){
              document.getElementById('result').innerHTML = 'An error occured. Status: ' + status;
           });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?signed_in=true"></script>
<div id='result'/>

Upvotes: 2

radu-matei
radu-matei

Reputation: 3520

I would make an array as a global variable with the number of elements as well a global variable. Then, in the callback I would increment the number of elements and set the current array element as the distance.

Hope this answers your question. Best of luck!

Upvotes: 1

Related Questions