Retrieve callback return

1

I have the function below that calculates distances using a Google API.

I would like to know how to get the callback function returned.

<script type="text/javascript" src="_global/_js/jquery-2.1.4.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false&key=my_key"></script><scripttype="text/javascript">
    function CalculaDistancia(origem, destino) {
        var service = new google.maps.DistanceMatrixService();
        service.getDistanceMatrix(  {
            origins: [origem],
            destinations: [destino],
            travelMode: google.maps.TravelMode.DRIVING
        }, callback);
        return callback;
    }
    function callback(response, status) {
        if (status == google.maps.DistanceMatrixStatus.OK) {
            distancia = response.rows[0].elements[0].distance.value;
            km = distancia/1000;
            kmr = Math.ceil(km/100);
            frete = kmr * 100;
            alert (frete);
        }
    }
</script>

<a href="javascript:CalculaDistancia('36880000', '28890185');">calcular</a>

As it is, alert(frete) normally alerts.

But I can not retrieve this value from within the CalculaDistancia() function.

    
asked by anonymous 16.10.2016 / 20:11

2 answers

1

When you have service.getDistanceMatrix({...}, callback); what happens is that this method takes two arguments. An object, and a function. And with that the function / method is consumed and the return will be passed to the callback.

Any content that service.getDistanceMatrix returns will be passed to the callback and you can no longer use within CalculaDistancia , at least as it is.

If you have more code that needs response, status then either insert that code into the callback, or change the callback passed to service.getDistanceMatrix . An example of the second option would look like this:

function CalculaDistancia(origem, destino) {
    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix(  {
        origins: [origem],
        destinations: [destino],
        travelMode: google.maps.TravelMode.DRIVING
    }, function(response, status){
       // aqui podes fazer algo com "response" e "status"
       // pois esta função é uma callback do método
       alert(response);
       // e depois:
       callback(response, status);
    });
    
16.10.2016 / 22:28
1

In addition to the suggested by Sergio , since Distance Matrix is an asynchronous service, you can use an Promise for asynchronous processing.

See an example:

function CalculaDistancia(origem, destino) {
  return new Promise(function(resolve, reject) {
    var service = new google.maps.DistanceMatrixService();

    service.getDistanceMatrix({
      origins: [origem],
      destinations: [destino],
      travelMode: google.maps.TravelMode.DRIVING
    }, 
    function(response, status) {
      if (status == google.maps.DistanceMatrixStatus.OK) {
          resolve(response);
      } else {
          reject(status);
      }
    }); 
  });
}
                                          
CalculaDistancia('36880000', '28890185')
  .then(function(response) {
     distancia = response.rows[0].elements[0].distance.value;

     km = distancia/1000;
     kmr = Math.ceil(km/100);

     frete = kmr * 100;
     console.log('O valor do frete é: ' + frete);

   }, function(status) {
     console.log('Não foi possível realizar a operação! Status: ' + status);
});
<script src="http://maps.google.com/maps?file=api&v=3&sensor=false&key=TUA_KEY_AQUI"></script>

Note:InplaceofTUA_KEY_AQUIplaceyourkey,ifyoudonothaveit,here'showtogetit:#

Get a Key / Authentication

See also:

16.10.2016 / 23:25