// adapted from developers.google.com/apps-script/quickstart/macros
function drivingDistance(origin, waypoint, destination) {
var directions = getDirections_(origin, destination);
return directions.routes[0].legs[0].distance.value;
}
function getDirections_(origin, waypoint, destination) {
var directionFinder = Maps.newDirectionFinder();
directionFinder.setOrigin(origin);
directionFinder.addWaypoint(waypoint);
directionFinder.setDestination(destination);
var directions = directionFinder.getDirections();
if (directions.routes.length == 0) {
throw 'Unable to calculate directions between these addresses.';
}
return directions;
}
This script originally checked column A for origin and then checked column B for destination. I was trying to use the addWaypoint function to add a 3rd point, but have been unsuccessful. I read through the API and tried a few different variations, but am afraid that I was again unsuccessful. How do I add multiple destinations or waypoints
When there are multiple waypoints, a
route
will consist of multiplelegs
, each of which has its owndistance
. So once you have the route calculated, you still need to go through each of the legs and sum up the individual distances to arrive at a final value.Once we have this figured out for one mid-point, surely we'll want it for two. And once we have it for two, why not three? Finally, why not an arbitrary number of waypoints?
See Accept Arbitrary Number of Arguments in Google Scripts Custom Function? for an example of how a custom function with arbitrary parameters will behave in a Spreadsheet.
This modified script handles a route with any number of points. It's fully supported by Auto-completion within Sheets. And it can handle a list of waypoints, or a range of cells. It's also copiously commented to explain each step.
Basic use:
More advanced use, with a more understandable output:
Code
Enough jabbering, just give me teh codez! (Updated code is available on gist.github.com.)
A parameter was missing in
function drivingDistance()
. I changedto
Here's the updated code, with a test function
Good luck with this. Learning how to program takes time. I suggest you find a website that teaches Java Script. Hope you get it working with the spreadsheet.
PS: If you'd like a more readable result, you could change the last line of
drivingDistance()
to givedistance.text
instead ofdistance.value
. In the London-Manchester-Liverpool example, the result would be"322 km"
.