Recover return from callback

Asked

Viewed 530 times

1

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

I would like to know how to have the return of the function of callback.

<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>
<script type="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 stands, the alert(frete) normally alert.

But I can’t recover that value from inside the function CalculaDistancia().

  • Google Maps API Warning: Sensornotrequired https://developers.google.com/maps/documentation/javascript/error-messages#sensor-not-required

  • just like that

  • Carlos, have you ever tried any of the solutions? Is there anything left to add to any of them?

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

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

If you have more code than I need response, status then either insert this code into the callback, or change the callback passed to service.getDistanceMatrix. An example of the second option would be 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);
    });
  • In the case of if (status == ...) { it is more appropriate to settle in the callback of service.getDistanceMatrix or in function callback? +1

  • 1

    @stderr depends on the structure and logic of the code. It is difficult to answer in general. +1 also for your answer.

1

Beyond the alternative suggested by Sergio, since Distance Matrix is an asynchronous service, you can use an Promise for asynchronous processing.

Take 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: In place of TUA_KEY_AQUI put your key, if you don’t have it, see how to get on this page: Get a Key/Authentication.

See also:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.