How to return to "waypoint_order" in the Google Directions API?

Asked

Viewed 867 times

8

I’m developing a route mapping system using the Google Maps API.

I have the points of origin and destination and between those points there are some points of interest. When plotting the route Google returns me the best route and mark these points on the map. I display the route data in a div.

My function that calculates the route, the part that returns the data looks like this:

directionsService.route(request, $.proxy(function(response, status){

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

    directionsDisplay.setDirections(response);
    var orders = response.routes[0].waypoint_order; 
    var route = response.routes[0];
    var total_distance = 0;
    var displayRoute = $('#detail-route');

    for (i = 0; i < route.legs.length; i++){

      var routeSegment = i + 1,
      from_address = route.legs[i].start_address.split(','),
      to_address = route.legs[i].end_address.split(',');
      total_distance += Math.floor(route.legs[i].distance.value / 1000);

      displayRoute.append('<b>Trecho ' + routeSegment + ': </b><br/>');
      displayRoute.append('<b>Saindo de: </b>' + from_address[0] + '<br/>');
      displayRoute.append('<b>Indo para: </b>' + to_address[0] + '<br/>');
      displayRoute.append('<b>Distância: </b>' + route.legs[i].distance.text);
    }

    displayRoute.prepend('total:' + this.format(total_distance) + ' km' + '<br/><br/>');

function format() is my function to format km.

The problem is that, in some routes, the waypoint_order shows a different order.

For example:

For a given route, the route.legs[i] returns order:

waypoint 0, 1 waypoint, waypoint 3, waypoint 2

but the returns waypoint_orderattribute [3, 0, 2, 1, 3].

Question

Is this the expected behavior, or is something missing?

  • Did I get this to work? If the answer below is correct you can accept it. If you can’t answer it yourself so others can use it in the future...

  • 1

    It’s not working yet.

1 answer

3

I imagine you put the optimizeWaypoints: true, taken from the documentation of the Google Directions API:

waypoint_order contains an array indicating the order of any waypoints in the calculated route. This waypoints may be reordered if the request was passed optimize:true Within its waypoints Parameter.

In free translation:

waypoints_order contains an array indicating the order of all waypoints within the calculated route. These waypoints may be recovered if it is passed optimize:true in the request, next to the parameter waypoints.

That is, if you want to optimize the route, the path points can have their route reorganized and, perhaps for this reason, the order in the route.legs is different from the order of waypoints.

Browser other questions tagged

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