-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
112 lines (96 loc) · 3.02 KB
/
index.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const fetch = require("node-fetch");
const fs = require("fs");
const tsvFormat = require("d3-dsv").tsvFormat;
const mkdirp = require("mkdirp");
const settings = { method: "Get" };
const flightId = process.argv[2] || "21b736e8", // example
url =
"https://api.flightradar24.com/common/v1/flight-playback.json?flightId=",
jsonURL = url + flightId;
fetch(jsonURL, settings)
.then(res => res.json())
.then(json => {
const data = json.result.response.data.flight,
track = data.track;
if (track) {
const csv = [];
track.forEach(function(d) {
const row = {},
keys = Object.keys(d);
keys.forEach(function(str) {
if (typeof d[str] == "object" && d[str] != null) {
const subKeys = Object.keys(d[str]);
subKeys.forEach(function(subKey) {
row[str + "_" + subKey] = d[str][subKey];
});
} else if (d[str] != null) {
row[str] = d[str];
}
});
csv.push(row);
});
// Export to GeoJSON
const geojson = {};
geojson["type"] = "FeatureCollection";
geojson["features"] = [];
const coordinates = [],
properties = [];
track.forEach(function(e) {
const pair = [];
pair.push(e.longitude);
pair.push(e.latitude);
coordinates.push(pair);
properties.push({
altitude: e.altitude,
verticalSpeed: e.verticalSpeed,
speed: e.speed
});
});
const feature = {
type: "Feature",
geometry: {
type: "LineString",
coordinates: coordinates
},
properties: properties
};
geojson["features"].push(feature);
// parsing as tsv file
const csvFormated = tsvFormat(csv);
/// get origin and destination names to use them in file name
const origin = clearPropName("origin");
const dest = clearPropName("destination");
mkdirp("data", function(err) {
if (err) console.error(err);
else {
const fileName = `${flightId}_${origin}_to_${dest}`;
fs.writeFile(`data/${fileName}.tsv`, csvFormated, function(
err,
result
) {
if (err) console.log("error", err);
else console.log(`File ${fileName}.tsv written successfully`);
});
fs.writeFile(
`data/${fileName}.geojson`,
JSON.stringify(geojson),
function(err, result) {
if (err) console.log("error", err);
else console.log(`File ${fileName}.geojson written successfully`);
}
);
}
});
} else {
console.log("Flight data not found");
}
// clear property name, replace spaces, etc.
function clearPropName(prop) {
const reg = /\s/gi;
if (data.airport[prop] && data.airport[prop].name) {
return data.airport[prop].name.toLowerCase().replace(reg, "_");
}
return "unknown";
}
})
.catch(err => console.log(err));