Google Distance Matrix need to return the value

后端 未结 2 1457
一个人的身影
一个人的身影 2021-02-11 07:15

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



        
相关标签:
2条回答
  • 2021-02-11 08:07

    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!

    0 讨论(0)
  • 2021-02-11 08:21

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

    0 讨论(0)
提交回复
热议问题