1

here is my code, the cb function does not get called from within the route function

function calcRoute(directionsService, data, i, cb) {
  var start;
  var end;
  var waypts = [];
  var date = data[i][0].rotaDate;
  var batches = [];
  var itemsPerBatch = 10; // google API max - 1 start, 1 stop, and 8 waypoints
  var itemsCounter = 0;
  var wayptsExist = 0;

  while (wayptsExist != data[i].length) {
    var subBatch = [];
    var subitemsCounter = 0;

    for (var j = itemsCounter; j < data[i].length; j++) {
      subitemsCounter++;
      var waypoint = new google.maps.LatLng(data[i][j].userLat, data[i][j].userLng);


      subBatch.push({
        location: waypoint,
        stopover: true
      });
      if (subitemsCounter == itemsPerBatch)
        break;
    }

    itemsCounter += subitemsCounter;
    batches.push(subBatch);
    //if(itemsCounter < data[i].length)
    wayptsExist = itemsCounter; // &amp;lt; data[i].length;
    // If it runs again there are still points. Minus 1 before continuing to
    // start up with end of previous tour leg
    itemsCounter--;

  }

  var combinedResults;
  var unsortedResults = [{}]; // to hold the counter and the results themselves as they come back, to later sort
  var directionsResultsReturned = 0;

  for (var k = 0; k < batches.length; k++) {
    var lastIndex = batches[k].length - 1;
    var start = batches[k][0].location;
    var end = batches[k][lastIndex].location;

    // trim first and last entry from array
    var waypts = [];
    waypts = batches[k];
    waypts.splice(0, 1);
    waypts.splice(waypts.length - 1, 1);
    var request = {
      origin: start,
      destination: end,
      waypoints: waypts,
      travelMode: window.google.maps.TravelMode.DRIVING
    };


    directionsService.route(request, function(result, status) {

      if (status == window.google.maps.DirectionsStatus.OK) {

        var unsortedResult = {
          order: k,
          result: result
        };
        unsortedResults.push(unsortedResult);

        directionsResultsReturned++;

        if (directionsResultsReturned == batches.length) // we've received all the results. put to map
        {
          // sort the returned values into their correct order
          unsortedResults.sort(function(a, b) {
            return parseFloat(a.order) - parseFloat(b.order);
          });
          var count = 0;
          var totalDist = 0;
          var totalTime = 0;
          for (var key in unsortedResults) {
            if (unsortedResults[key].result != null) {
              if (unsortedResults.hasOwnProperty(key)) {
                if (count == 0) // first results. new up the combinedResults object
                  combinedResults = unsortedResults[key].result;
                else {
                  // only building up legs, overview_path, and bounds in my consolidated object. This is not a complete
                  // directionResults object, but enough to draw a path on the map, which is all I need


                  combinedResults.routes[0].legs = combinedResults.routes[0].legs.concat(unsortedResults[key].result.routes[0].legs);
                  combinedResults.routes[0].overview_path = combinedResults.routes[0].overview_path.concat(unsortedResults[key].result.routes[0].overview_path);

                  combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getNorthEast());
                  combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getSouthWest());
                }
                count++;
              }
            }
          }
          var myroute = combinedResults.routes[0];
          for (i = 0; i < myroute.legs.length; i++) {
            totalDist += myroute.legs[i].distance.value;
            //totalTime += myroute.legs[i].duration.value;
          }
          totalDist = totalDist / 1000.

          //get result here
           cb();
        }
      } else {
        console.log('error ' + status);

      }
    });
    }       
}

this is the function that calls calRoute and passes the callback function in

function getMileage() {
  var data;

  var directionsService = new google.maps.DirectionsService();
  var url = '********/getdata.php';
  $.ajax({
    type: 'GET',
    url: url,
    //dataType: 'json',
    success: function(output) {

      data = $.parseJSON(output);
      var count = 0;
      var count2 = -1;
      var next = true;

      while (count != data.length) {
        if (next == true) {
          next = false;
          calcRoute(directionsService, data, count, function() {
            next = true;
          });
          count++;
        }
      }
    }
  });
}

this answer suggest i can do this but it is not working for me

9
  • You might wanna put your code through a linter because with the naked eye I can already spot a few mistakes. Fix the syntax error first. Commented Mar 6, 2017 at 19:35
  • @BramVanroy in which function? Commented Mar 6, 2017 at 19:36
  • In calcRoute. Find an editor that can do linting on-the-go. Commented Mar 6, 2017 at 19:38
  • i missed the last two brackets when copying, the code runs without error in the console and does what it needs to apart from the callback Commented Mar 6, 2017 at 19:40
  • @BramVanroy i use dreamweaver with linting enabled, i get shown most syntax errors Commented Mar 6, 2017 at 20:21

1 Answer 1

1

You have a typo in your function call.

Wrong

      totalDist = totalDist / 1000.

      //get result here
       cb();

Right

      totalDist = totalDist / 1000;

      //get result here
       cb();
Sign up to request clarification or add additional context in comments.

4 Comments

thanks, not sure why the lint running in dreamweaver doesn't show that??
@Rob85 It's not an error, and I was wrong in suggesting it was an error a linter could catch (even though that was necessary). It's valid JS to write a method to a numeric literal, e.g. 123.aMethod(). See this link.
although that was an error cb() is still not called
@Rob85 It should work, though. See this base example. Try doing a console.log right before you call cb(). Perhaps the function never gets that far.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.