title: Callback inside an Angular Service - how to return data to controller
body: <p>I am using Google Maps API to get the distance between two points. This method uses a callback function. The problem is that this code lies inside an Angular service, which I want to be called from a controller so the controller can output the results in the scope. But I have no idea how the service can return the resulting <strong>hospitals[]</strong> array of objects to the controller. How can i accomplish this?</p>
  
  <pre><code>myAppServices.service('NearestHospitalService', function(){
  function calculateDistances() {
          var service = new google.maps.DistanceMatrixService();
          var hospitals = [];
          service.getDistanceMatrix(
          {
            origins: [origin1],
            destinations: [destinationA, destinationB],
            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;
              var destinations = response.destinationAddresses;
              var results = response.rows[0].elements;
              for (var j = 0; j &lt; results.length; j++) {
                  hospitals.push(new hospital(destinations[j], results[j].distance, results[j].duration));
              }
              hospitals.sort(compareDistance);
          }
      }
  });
  </code></pre>