title: Looping Multiple Origins for Google Maps Direction Services
body: <p>I'd like to find the shortest driving distance for multiple origins to multiple destinations. Say I have 5 customers and 10 stores, I'd like to find the shortest distance for each customer to a store. </p>
  
  <p>My problem now is the 10 query per second limit on the google direction service. For each customer it takes less than 1 second to finish querying the API, so I will reach the query limit for each customer. </p>
  
  <p>I tried to implement a delay between each customer, but the callback function from the google direction service is not blocked...</p>
  
  <pre><code>  // A function to calculate the route between our current position and some desired end point.
    function calcRoute(end, callback) {
      var request = {
          origin: currentPosition,
          destination: end,
          travelMode: google.maps.TravelMode.DRIVING
      };
      directionsService.route(request, function(response, status) {
  
        if (status == google.maps.DirectionsStatus.OK) {
          callback(response);
        } else {
          size--;
        }
      });
    }
  
    // Stores a routing result from the API in our global array for routes.
    function storeResult(data) {
      routeResults.push(data);
      if (routeResults.length === size) {
        findShortest();
      }
    }
  
    // Goes through all routes stored and finds which one is the shortest. It then
    // sets the shortest route on the map for the user to see.
    function findShortest() {
      var i = routeResults.length;
      var shortestIndex = 0;
      var shortestLength = routeResults[0].routes[0].legs[0].distance.value;
  
      while (i--) {
        if (routeResults[i].routes[0].legs[0].distance.value &lt; shortestLength) {
          shortestIndex = i;
          shortestLength = routeResults[i].routes[0].legs[0].distance.value;
        }
      }
      directionsDisplay.setDirections(routeResults[shortestIndex]);
    }
  </code></pre>
  
  <p>Is there a way to block the callback after each iteration? Or is there another way to do this?</p>