[TypeScript] コマンドライン引数から緯度・経度から距離を測定したい

$ npm install @turf/distance
$ npm install @turf/helpers

index.ts

1
2
3
4
5
6
7
import distance from '@turf/distance'
import { point } from '@turf/helpers'
 
const tokyo = point([139.69198077115493, 35.68978025468156])
const osaka = point([135.51980022509665, 34.6865543538711])
const result = distance(tokyo, osaka, {units: 'kilometers'})
console.log(result)

$ node sample.js
395.1818245563336

これをコマンドライン引数で書くと

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import distance from '@turf/distance'
import { point } from '@turf/helpers'
 
console.log("Node path = " + process.argv[0])
console.log("Script file path = " + process.argv[1])
 
const startLongitude = Number(process.argv[2])
const startLatitude = Number(process.argv[3])
const destLongitude = Number(process.argv[4])
const destLatitude = Number(process.argv[5])
 
const start = point([startLongitude, startLatitude])
const dest = point([destLongitude, destLatitude])
const result = distance(start, dest, {units: 'kilometers'})
console.log(result)

これにアロー関数を追加する

1
2
3
4
5
6
7
const f = (name:string, speed:number): void => {
    let time = result / speed
    console.log("時速" + speed + "km/hの" + name + "だと、" + time + "時間かかります。")
}
 
f("新幹線", 200)
f("高速バス", 120)

$ node sample.js 139.69198077115493 35.68978025468156 135.51980022509665 34.6865543538711
395.1818245563336
時速200km/hの新幹線だと、1.975909122781668時間かかります。
時速120km/hの高速バスだと、3.29318187130278時間かかります。

process.argvを変数に代入すると冗長になるから直接書いても良さそうだな
高速バスで東京大阪は3.2時間以上かかるから、実際のところ60km/h ってところか。

うむ、書きながら勉強になるな