/**
* Calculate the distance between two
* locations on Google Maps.
*
* =GOOGLEMAPS_DISTANCE("NY 10005", "Hoboken NJ", "walking", value_or_array)
*
* @param {String} origin The address of starting point
* @param {String} destination The address of destination
* @param {String} mode The mode of travel (driving, walking, bicycling or transit)
* @param {String|Array} waypoints To include as part of route
* @return {String} The distance in KM
* @customFunction
*/
const GOOGLEMAPS_DISTANCE = (origin, destination, mode, waypoints) => {
const route = Maps.newDirectionFinder()
.setOrigin(origin)
.setDestination(destination)
.setMode(mode);
if(waypoints){
Array.isArray(waypoints) ?
waypoints.map(row => row.map(cell => route.addWaypoint(cell))) :
route.addWaypoint(waypoints);
}
const { routes: [data] = [] } = route.getDirections();
if (!data) {
throw new Error('No route found!');
}
const { legs: [{ distance: { text: distance } } = {}] = [] } = data;
return distance;
};