Skip to content

Instantly share code, notes, and snippets.

@mammuth
Last active July 17, 2019 18:33
Show Gist options
  • Save mammuth/28f2e64084f2d37cf3012217ea87082a to your computer and use it in GitHub Desktop.
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
/*
* 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