Skip to content

Instantly share code, notes, and snippets.

@frohoff frohoff/Code.gs
Created Jun 17, 2017

Embed
What would you like to do?
google sheets directions/distance functions
function qs( obj ) {
return '?'+Object.keys(obj).reduce(function(a,k){a.push(k+'='+encodeURIComponent(obj[k]));return a},[]).join('&')
}
function fetch_directions(o,d) {
Logger.log("fetching: " + JSON.stringify([o,d]));
var userProps = UserProperties.getProperties();
var client = UserProperties.getProperty("client");
var apikey = UserProperties.getProperty("key");
Logger.log("keys: " + JSON.stringify([userProps, client, apikey]));
var url = "https://maps.googleapis.com/maps/api/directions/json"
return UrlFetchApp.fetch(url + qs({origin: o, destination: d, key: apikey}));
}
function directions(origin, destination) {
var cache = CacheService.getDocumentCache();
var key = [origin, destination];
Logger.log("key: " + JSON.stringify(key))
var directions_str = cache.get(key);
var directions = JSON.parse(directions_str);
if (directions == null || directions["status"] != "OK") {
Logger.log("calculating");
directions_str = fetch_directions(origin, destination);
directions = JSON.parse(directions_str);
cache.put(key, directions_str);
}
Logger.log("directions: " + JSON.stringify(directions));
if (directions["status"] != "OK") {
directions = directions["status"] + ": " + directions["error_message"];
}
return directions;
}
function directions_dist(origin, destination) {
var dir = directions(origin, destination);
Logger.log("dir: " + JSON.stringify(dir));
if (typeof dir != "object") return dir;
Logger.log("leg: " + JSON.stringify(dir.routes[0].legs[0]));
return dir.routes[0].legs[0].distance.value/1609.34;
}
function directions_dur(origin, destination) {
var dir = directions(origin, destination);
Logger.log("dir: " + JSON.stringify(dir));
if (typeof dir != "object") return dir;
Logger.log("leg: " + JSON.stringify(dir.routes[0].legs[0]));
return dir.routes[0].legs[0].duration.value/3600;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.