I’m using the Google Maps API to get driving distances from multiple routes. Each route is being taken by a different driver; they all have the same start point but different endpoints and might have multiple waypoints.
The problem I’m having is that the API doesn’t seem to give me any way to name each route, so when they come back asynchronously, I can’t be sure which route belongs to which driver. It’s true that each route has different addresses, but the DirectionsService response object gives me back slightly different addresses than I send — “Des Plaines, IL” becomes “Des Plaines, IL, USA”, for instance — making it unreliable to compare those.
The API doesn’t seem to let me send arbitrary strings with the request object to name them uniquely. So what can I do?
A code snippet that might help clarify what I’m doing:
$.getJSON(ajaxsource, function(data) {
var darr = data.driver_info, // includes driver name, start and end addresses
driver, start, end,
waypts = [];
for (var i=0,j=darr.length; i<j; i++) {
if (driver==$.trim(darr[i][8])) { // same driver, next destination
// start = end;
waypts.push({
location: end,
stopover: true });
} else {
waypts = [];
driver = $.trim(darr[i][8]);
start = $.trim(darr[i][4]);
}
end = $.trim(darr[i][2]);
if (i+1==j || driver!=$.trim(darr[i+1][8])) {
var request = { // route object
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsDisplay = new google.maps.DirectionsRenderer();
directionsService.route(request, function(response, status) {
var legs = response.routes[0].legs;
// console.log(response);
for (var k=0; k<legs.length; k++) {
$('#results').append($('<li>').html("Driver " + driver +
"<br>starts at " + legs[k].start_address +
"<br>and drives " + legs[k].distance.text +
"<br>to end at " + legs[k].end_address));
}
});
};
}; // end for
}); // end getJSON
That code will return all the route info as desired, but since it’s asynchronous, the driver in each result is the name of the last driver listed in my data.driver_info array. What I need is to list the driver that should be associated with that particular route.
A little more debugging uncovered a solution — the Google documentation didn’t mention that the
responseobject doesn’t just contain a status and routes, but also a sub-object calledubwhich mirrors the request object I sent. Using that, I can compare addresses exactly to match routes to drivers.I added the following code inside my
directionsService.route()callback: