-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.js
90 lines (75 loc) · 2.35 KB
/
lib.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const maps = require('@google/maps');
const polyline = require('@mapbox/polyline');
const tokml = require('tokml');
const togpx = require('togpx');
const geojson = require('geojson');
const topojson = require('topojson');
const util = require('util');
const { URL } = require('url');
// private
function convertDataPoint(dataPoint) {
if (typeof dataPoint == "string") {
return dataPoint;
}
return dataPoint.split(',').map(parseFloat);
}
function convertDirections(directionsObject, toFormat) {
const normalizedPoints = [];
const decodedPoints = polyline.decode(directionsObject.json.routes[0].overview_polyline.points);
for(let point of decodedPoints) {
const value = [point[1],point[0]];
normalizedPoints.push(value);
}
const data = { line: normalizedPoints };
const geoData = geojson.parse(data, { "LineString": "line" });
switch(toFormat) {
case "GPX":
console.log(togpx(geoData));
break;
case "KML":
console.log(tokml(geoData));
break;
case "TopoJSON":
console.log(JSON.stringify(topojson.topology(geoData)));
break;
default:
console.log(JSON.stringify(geoData, null, 2));
}
process.exit(0);
}
// public
function GetMapsObject(googleMapsURL) {
const urlObject = new URL(googleMapsURL);
const urlObjectArray = urlObject.pathname.split('/')
const googleMapsObject = {
origin: convertDataPoint(urlObjectArray[3]),
destination: convertDataPoint(urlObjectArray[4]),
waypoints: []
};
// extract way points from url data parameter
const parts = urlObjectArray[6].split('=')[1].split('!');
const indexes = parts.map((e, i) => (e === "2m2" || e === "1m2") ? i : '').filter(String);
for(let index of indexes) {
googleMapsObject.waypoints.push([
parseFloat(parts[index+2].split('d')[1]),
parseFloat(parts[index+1].split('d')[1])
]);
}
return googleMapsObject;
}
function GetDirections(directionRoute, toFormat) {
const googleMapsClient = maps.createClient({
Promise: global.Promise,
key: process.env.GOOGLE_MAPS_API_KEY
});
googleMapsClient.directions(directionRoute)
.asPromise()
.then(response => {
convertDirections(response, toFormat)
})
.catch((err) => {
console.error('Error: Unable to parse URL and generate output');
process.exit(0);
});
}
module.exports = { GetMapsObject, GetDirections };