Skip to content

Instantly share code, notes, and snippets.

@itailulu
Created January 28, 2024 06:59
Show Gist options
  • Save itailulu/9b96324355ecf711377cb9e390ccbebd to your computer and use it in GitHub Desktop.
Save itailulu/9b96324355ecf711377cb9e390ccbebd to your computer and use it in GitHub Desktop.
Google Apps Script - Get Driving Distance
/**
* A custom function that gets the driving distance between two addresses.
*
* @param {String} origin The starting address.
* @param {String} destination The ending address.
* @return {Number} The distance in meters.
*/
function drivingDistance(origin, destination) {
const directions = getDirections(origin, destination);
return directions.routes?.[0]?.legs?.[0]?.distance?.value || 'Error';
}
/**
* A shared helper function used to obtain the full set of directions
* information between two addresses. Uses the Apps Script Maps Service.
*
* @param {String} origin The starting address.
* @param {String} destination The ending address.
* @return {Object} The directions response object.
*/
function getDirections(origin, destination) {
const directionFinder = Maps.newDirectionFinder();
directionFinder.setOrigin(origin);
directionFinder.setDestination(destination);
const directions = directionFinder.getDirections();
if (directions.status !== 'OK') {
// throw directions.error_message;
return 'ERROR: ' + directions.status
}
return directions;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment