Last active
July 17, 2019 18:33
-
-
Save mammuth/28f2e64084f2d37cf3012217ea87082a to your computer and use it in GitHub Desktop.
Calculate your transit time between 1-n locations. Use if you want to compare travel time from a new flat to your favorite spots
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
/* | |
* What? | |
* A JavaScript script that prints out travel times between one origin and multiple targets. | |
* | |
* Example output | |
* $ node apartment-distances.js | |
* Marienplatz, Munich "24 mins" | |
* Google Munich "25 mins" | |
* Jetbrains GmbH, Munich "26 mins" | |
* | |
* Usage | |
* - npm i node-fetch --save | |
* - create api key for google directions api | |
* - update the variables below | |
* - run node apartment-distances.js | |
*/ | |
const fetch = require("node-fetch"); | |
let apiKey = '<your-key-here>' | |
let travelMode = 'transit' // driving, transit, bicycling, walking | |
let origin = '<address-of-your-starting-point>' | |
let destinations = [ | |
'Marienplatz, Munich', | |
'Google München', | |
] | |
function getRouteDetails(origin, destination) { | |
let originEncoded = encodeURI(origin) | |
let destinationEncoded = encodeURI(destination) | |
let requestUrl = `https://maps.googleapis.com/maps/api/directions/json?origin=${originEncoded}&destination=${destinationEncoded}&key=${apiKey}&mode=${travelMode}` | |
fetch(requestUrl).then(response => { | |
if (!response.ok) { | |
throw response | |
} | |
return response.json() | |
}).then(data => { | |
console.log(destination, JSON.stringify(data['routes'][0]['legs'][0]['duration']['text'])) | |
}).catch(err => { | |
err.text().then(errorMessage => { | |
console.log(errorMessage) | |
}) | |
}) | |
} | |
destinations.map( dest => | |
getRouteDetails(origin, dest) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment