Created
February 16, 2016 22:54
-
-
Save jweaver/153bc05f0aec72c143a7 to your computer and use it in GitHub Desktop.
Use the google matrix API to get the distance in miles from one location to another. This requires the google API Key somewhere in the spreadsheet.
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
/** | |
* @OnlyCurrentDoc Limits the script to only accessing the current spreadsheet. | |
*/ | |
/** | |
* Take two string addresses, and use the google matrix distance API to | |
* fetch the mileage (distance) between the two. | |
* | |
* @param {String} origin An Address that resolves in Google Maps. The Origin. | |
* @param {String} destination Another address that varies from the first and | |
* resolves in Google Maps. The Destination. | |
* @param {String} apiKey The API Key to the Google Matrix API, see: | |
https://developers.google.com/maps/documentation/distancematrix/intro | |
* @return {String} the mileage text distance between both addresses. | |
*/ | |
function GET_DISTANCE(origin, destination, apiKey) { | |
Logger.log("Fetching distance between " + origin + " and " + destination); | |
var matrixHost = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="; | |
var encodedOrigin = encodeURIComponent(origin); | |
var encodedDestination = encodeURIComponent(destination); | |
var requestUrl = matrixHost + encodedOrigin + "&destinations=" + encodedDestination | |
+ "&key=" + apiKey + "&units=imperial"; | |
var resp = UrlFetchApp.fetch(requestUrl); | |
Logger.log(resp); | |
var jsonData = JSON.parse(resp); | |
return jsonData.rows[0].elements[0].distance.text; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment