-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch-metar.js
More file actions
373 lines (329 loc) · 13.1 KB
/
fetch-metar.js
File metadata and controls
373 lines (329 loc) · 13.1 KB
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
window.addEventListener('click', function (e) {
let div = document.querySelector("#search-block");
if (document.getElementById('query').contains(e.target)) {
div.classList.remove("visually-hidden");
} else {
div.classList.add("visually-hidden");
}
});
let sizeOrder = {
large_airport: 0,
medium_airport: 1,
small_airport: 2,
seaplane_base: 3,
heliport: 4,
closed: 5,
};
let cloudDesc = {
FEW: "Few",
SCT: "Scattered",
BKN: "Broken",
OVC: "Overcast",
CLR: "Clear",
SKC: "Sky Clear",
VV: "Vertical Visibility"
};
let latestMetars = [];
let latestAirports = []
function submit() {
document.body.classList.add('search-active');
document.querySelector("#results-container").classList.remove('visually-hidden');
getMetar();
}
function showError(message) {
let errorBox = document.getElementById('error');
if (message) {
errorBox.textContent = message;
errorBox.classList.remove('visually-hidden');
} else {
errorBox.classList.add('visually-hidden');
}
}
async function getMetar() {
let airports = document.querySelector("#query").value
.split(/\s+/)
.filter(code => /^[A-Za-z0-9]{4}$/.test(code))
.join();
if (airports === "") {
showError("Please enter a valid airport identifier");
return;
}
let airport_response = await fetch(`https://wx-backend.eruegg.com/airport/${airports}`).catch((err) => {
console.error("Error fetching airport data:", err);
showError("Failed to fetch airport data. Please try again");
});
let airport_data = await airport_response.json();
let metar_response = await fetch(`https://wx-backend.eruegg.com/metar/${airports}`).catch((err) => {
console.error("Error fetching METAR data:", err);
showError("Failed to fetch METAR data. Please try again");
});
metar_data = await metar_response.json();
if (metar_data.results === 0) {
showError("This airport has no METAR");
return;
}
showError("");
latestMetars = await metar_data.data;
latestAirports = await airport_data;
displayMetarCards();
}
function displayMetarCards() {
let container = document.querySelector(".results");
while (container.children.length > 0) {
container.removeChild(container.lastChild);
}
latestMetars.forEach((metar, idx) => {
// Card container
let card = document.createElement("div");
card.className = "card mb-3";
// Card header
let header = document.createElement("div");
header.className = "card-header";
header.innerHTML = `<strong>${metar.icao || metar.station || "Unknown"}</strong> — ${metar.station ? metar.station.name || "" : ""}`;
card.appendChild(header);
// Card body
let body = document.createElement("div");
body.className = "card-body";
// Prepare all list items
let items = [];
// Time
let liTime = document.createElement("li");
liTime.className = "list-group-item";
liTime.innerHTML = `<span class="badge text-bg-primary rounded-pill">DATE</span> <span>${new Date(metar.observed + "Z").toUTCString()}</span>`;
items.push(liTime);
// Winds (with gusts)
let windId = getSelectedRadioId("winds");
let windUnitMap = {
"option-kts": ["speed_kts", "kts"],
"option-kph": ["speed_kph", "kph"],
"option-mph": ["speed_mph", "mph"],
};
let [windSpeedKey, windLabel] = windUnitMap[windId] || windUnitMap["option-kts"];
let windDegrees = metar.wind.degrees;
let windSpeed = metar.wind[windSpeedKey];
let windGust = metar.wind[`gust_${windLabel}`];
let gustText = windGust ? ` (gusts ${windGust} ${windLabel})` : "";
let liWinds = document.createElement("li");
liWinds.className = "list-group-item";
liWinds.innerHTML = `<span class="badge text-bg-success rounded-pill">WINDS</span> <span>${windDegrees}° / ${windSpeed} ${windLabel}${gustText}</span>`;
items.push(liWinds);
// --- Runway/Wind Diagram ---
/*let airport = latestAirports[idx];
console.log("Airport data:", latestAirports);
let rwyDirections = [];
airport.runways.forEach((rwy) => {
rwyDirections.push({
"rwy_mag": rwy.alignment,
"rwy_num": rwy.id.split('/')[0],
"wind_deg": windDegrees-rwy.alignment,
});
rwyDirections.push({
"rwy_mag": rwy.alignment+180,
"rwy_num": rwy.id.split('/')[1],
"wind_deg": windDegrees-(rwy.alignment+180),
});
});
console.log("Runway directions:", rwyDirections);
let smallestAngle = 360;
let bestRwy = null;
rwyDirections.forEach((rwy, index) => {
if (rwy.wind_deg < smallestAngle) {
smallestAngle = rwy.wind_deg;
bestRwy = rwy;
}
});
let runwayHeading = bestRwy.rwy_mag;
let runwayLabel = bestRwy.rwy_num;
let rwy1 = runwayLabel.replace(/\D/g, '');
let rwy2 = rwy1 + 18;
let windRelative = bestRwy.wind_deg;
// SVG size and center
let svgSize = 60;
let center = svgSize / 2;
let runwayLength = 40;
let windLength = 25;
// Runway line (vertical)
let runwayY1 = center - runwayLength / 2;
let runwayY2 = center + runwayLength / 2;
// Wind vector: 0° is north (up)
let windRad = (windRelative - 0) * Math.PI / 180;
let windX = center + windLength * Math.sin(windRad);
let windY = center - windLength * Math.cos(windRad);
let svg = `
<svg width="${svgSize}" height="${svgSize}" style="vertical-align:middle;margin-left:10px">
<!-- Runway line -->
<line x1="${center}" y1="${runwayY1}" x2="${center}" y2="${runwayY2}" stroke="#333" stroke-width="4" />
<!-- Runway label at both ends -->
<text x="${center}" y="${runwayY1 - 4}" text-anchor="middle" font-size="10" fill="#333">${rwy2}</text>
<text x="${center}" y="${runwayY2 + 14}" text-anchor="middle" font-size="10" fill="#333">${rwy1}</text>
<!-- Wind line (no arrowhead) -->
<line x1="${center}" y1="${center}" x2="${windX}" y2="${windY}" stroke="#1976d2" stroke-width="3" />
</svg>
`;
liWinds.innerHTML += svg;*/
// Temperature
let tempId = getSelectedRadioId("temp");
let tempUnitMap = {
"option-celsius": ["temperature", "celsius", "°C"],
"option-fahrenheit": ["temperature", "fahrenheit", "°F"],
};
let [tempObjKey, tempValKey, tempLabel] = tempUnitMap[tempId] || tempUnitMap["option-celsius"];
let temperature = metar.temperature ? (metar.temperature[tempValKey] + " " + tempLabel) : "N/A";
let liTemp = document.createElement("li");
liTemp.className = "list-group-item";
liTemp.innerHTML = `<span class="badge text-bg-warning rounded-pill">TEMPERATURE</span> <span>${temperature}</span>`;
items.push(liTemp);
// Dewpoint
let dewpoint = metar.dewpoint ? (metar.dewpoint[tempValKey] + " " + tempLabel) : "N/A";
let liDew = document.createElement("li");
liDew.className = "list-group-item";
liDew.innerHTML = `<span class="badge text-bg-danger rounded-pill">DEWPOINT</span> <span>${dewpoint}</span>`;
items.push(liDew);
// Visibility
let visId = getSelectedRadioId("vis");
let visUnitMap = {
"option-vis-sm": ["miles", "sm"],
"option-vis-m": ["meters", "m"],
};
let [visKey, visLabel] = visUnitMap[visId] || visUnitMap["option-vis-sm"];
let visValue = metar.visibility && metar.visibility[visKey] !== undefined ? metar.visibility[visKey] : "N/A";
let liVis = document.createElement("li");
liVis.className = "list-group-item";
liVis.innerHTML = `<span class="badge text-bg-dark rounded-pill">VISIBILITY</span> <span>${visValue} ${visValue !== "N/A" ? visLabel : ""}</span>`;
items.push(liVis);
// Clouds
let liClouds = document.createElement("li");
liClouds.className = "list-group-item";
liClouds.innerHTML = `<span class="badge text-bg-light rounded-pill">CLOUDS</span>`;
let cloudUnitId = getSelectedRadioId("height");
let cloudUnitMap = {
"option-ft": ["base_feet_agl", "ft"],
"option-m": ["base_meters_agl", "m"],
};
let [cloudBaseKey, cloudBaseLabel] = cloudUnitMap[cloudUnitId] || cloudUnitMap["option-ft"];
if (Array.isArray(metar.clouds) && metar.clouds.length > 0) {
let sortedClouds = [...metar.clouds].sort((a, b) => {
let aVal = a[cloudBaseKey] ?? Infinity;
let bVal = b[cloudBaseKey] ?? Infinity;
return bVal - aVal;
});
let cloudsHtml = sortedClouds.map(cloud => {
let desc = cloudDesc[cloud.code] || cloud.code;
let base = (cloud[cloudBaseKey] !== undefined && cloud[cloudBaseKey] !== null) ? `${cloud[cloudBaseKey]} ${cloudBaseLabel}` : "";
let type = cloud.type ? ` (${cloud.type})` : "";
let isCeiling = cloud.code === "BKN" || cloud.code === "OVC";
return `<div class="cloud-layer${isCeiling ? " cloud-ceiling" : ""}">
<span class="cloud-text">${desc}${base ? " " + base : ""}${type}</span>
<span class="cloud-underline"></span>
</div>`;
}).join("");
liClouds.innerHTML += `<div>${cloudsHtml}</div>`;
} else {
liClouds.innerHTML += `<span>Clear</span>`;
}
items.push(liClouds);
// Altimeter
let altimId = getSelectedRadioId("altimeter");
let altimeterUnitMap = {
"option-hg": ["barometer", "hg", "Hg"],
"option-mb": ["barometer", "mb", "mb"],
"option-hpa": ["barometer", "hpa", "hPa"],
};
let [altimObjKey, altimValKey, altimLabel] = altimeterUnitMap[altimId] || altimeterUnitMap["option-hg"];
let liAltim = document.createElement("li");
liAltim.className = "list-group-item";
liAltim.innerHTML = `<span class="badge text-bg-info rounded-pill">ALTIMETER</span> <span>${metar[altimObjKey][altimValKey]} ${altimLabel}</span>`;
items.push(liAltim);
// Pressure Altitude
let densityAlt = "N/A";
let pressureAlt = "N/A";
if (metar.elevation && metar.elevation.feet && metar.barometer && metar.barometer.hg) {
let pa = Math.round(
Number(metar.elevation.feet) + (29.92 - Number(metar.barometer.hg)) * 1000
);
pressureAlt = pa + " ft";
}
if (
metar.elevation && metar.elevation.feet &&
metar.barometer && metar.barometer.hg &&
metar.temperature && typeof metar.temperature.celsius === "number"
) {
let pa = Number(metar.elevation.feet) + (29.92 - Number(metar.barometer.hg)) * 1000;
let isa = 15 - (2 * Number(metar.elevation.feet) / 1000);
let da = Math.round(pa + 120 * (Number(metar.temperature.celsius) - isa));
densityAlt = da + " ft";
}
let liPA = document.createElement("li");
liPA.className = "list-group-item";
liPA.innerHTML = `<span class="badge text-bg-secondary rounded-pill">PRESSURE ALT</span> <span>${pressureAlt}</span>`;
items.push(liPA);
let liDA = document.createElement("li");
liDA.className = "list-group-item";
liDA.innerHTML = `<span class="badge text-bg-secondary rounded-pill">DENSITY ALT</span> <span>${densityAlt}</span>`;
items.push(liDA);
// Split into two columns
let col1 = document.createElement("ul");
col1.className = "list-group";
let col2 = document.createElement("ul");
col2.className = "list-group";
// Adjust the split as you like; here, half and half
let mid = Math.ceil(items.length / 2);
items.slice(0, mid).forEach(item => col1.appendChild(item));
items.slice(mid).forEach(item => col2.appendChild(item));
let row = document.createElement("div");
row.className = "row";
let colDiv1 = document.createElement("div");
colDiv1.className = "col-12 col-md-6";
let colDiv2 = document.createElement("div");
colDiv2.className = "col-12 col-md-6";
colDiv1.appendChild(col1);
colDiv2.appendChild(col2);
row.appendChild(colDiv1);
row.appendChild(colDiv2);
body.appendChild(row);
// Raw METAR
let raw = document.createElement("div");
raw.className = "alert alert-light mt-3";
raw.textContent = metar.raw_text;
body.appendChild(raw);
card.appendChild(body);
container.appendChild(card);
});
}
// Helper to get selected radio id by group name
function getSelectedRadioId(name) {
let el = document.querySelector(`input[name="${name}"]:checked`);
return el ? el.id : null;
}
function blurSearch() {
if (document.querySelector("#results-container").classList.contains('visually-hidden') && document.getElementById('query').value == "") {
document.body.classList.remove('search-active');
}
}
// Attach event listeners once DOM is ready
document.addEventListener("DOMContentLoaded", () => {
document.querySelectorAll('input[type=radio]').forEach((input) => {
input.addEventListener("change", () => {
displayMetarCards();
});
});
let searchBox = document.getElementById('query');
searchBox.addEventListener("keypress", function (event) {
// If the user presses the "Enter" key on the keyboard
if (event.key === "Enter") {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
document.getElementById("submit-btn").click();
}
});
let settingsBtn = document.getElementById("settings-btn");
let settingsModal = document.getElementById("settingsModal");
// Toggle active class on modal show/hide
settingsModal.addEventListener('show.bs.modal', () => {
settingsBtn.classList.add('active');
});
settingsModal.addEventListener('hide.bs.modal', () => {
settingsBtn.classList.remove('active');
});
});