Google Distance Matrix need to return the value

我怕爱的太早我们不能终老 提交于 2021-02-18 03:39:11

问题


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!.


回答1:


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'/>



回答2:


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!



来源:https://stackoverflow.com/questions/32022112/google-distance-matrix-need-to-return-the-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!