Created
June 17, 2017 20:11
-
-
Save frohoff/1e589ffba22bf7c11c97fafe2fabd5fd to your computer and use it in GitHub Desktop.
google sheets directions/distance functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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