Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
595 lines (518 loc) · 20.1 KB
/
Copy pathscript.js
File metadata and controls
595 lines (518 loc) · 20.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
/**
* AeroPulse — Pollution Heatmap & Predictive Analytics Engine
* Advanced Leaflet Heatmap, Time-Series Forecast Simulation, and Dynamic Data Visualization
*/
// Application Central State
const AppState = {
activePollutant: "aqi",
currentTimeStepIndex: 0,
isPlaying: false,
playInterval: null,
selectedZone: null,
heatBlur: 25,
heatRadius: 32,
heatOpacity: 0.75,
map: null,
heatLayer: null,
markersGroup: null,
trendChart: null,
customZones: []
};
// Map Utility Helper
function getAQIColor(aqi) {
if (aqi <= 50) return "#10B981"; // Good
if (aqi <= 100) return "#F59E0B"; // Moderate
if (aqi <= 150) return "#F97316"; // Unhealthy Sensitive
if (aqi <= 200) return "#EF4444"; // Unhealthy
if (aqi <= 300) return "#8B5CF6"; // Very Unhealthy
return "#881337"; // Hazardous
}
function getRiskCategoryLabel(aqi) {
if (aqi <= 50) return "Good";
if (aqi <= 100) return "Moderate";
if (aqi <= 150) return "Elevated";
if (aqi <= 200) return "Unhealthy";
if (aqi <= 300) return "Severe";
return "Hazardous Peak";
}
// Initialize Application
document.addEventListener("DOMContentLoaded", () => {
initMap();
initPollutantSelectors();
initLayerControls();
initTimelineControls();
initSearch();
initModalUploader();
initExportEngine();
// Set default active zone
if (pollutionData.zones.length > 0) {
selectZone(pollutionData.zones[0]);
}
updateAllViews();
});
/* ==========================================================================
1. Leaflet Map Initialization
========================================================================== */
function initMap() {
// Initialize Leaflet map instance centered over India / South Asia region
AppState.map = L.map("map-container", {
center: [23.5, 78.5],
zoom: 5,
zoomControl: false,
minZoom: 3,
maxZoom: 14
});
// Add Leaflet zoom control to top-right
L.control.zoom({ position: "topright" }).addTo(AppState.map);
// Load CartoDB Dark Matter tile basemap for sleek geospatial contrast
L.tileLayer("https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png", {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors © <a href="https://carto.com/attributions">CARTO</a>',
subdomains: "abcd",
maxZoom: 19
}).addTo(AppState.map);
// Initialize LayerGroup for markers
AppState.markersGroup = L.layerGroup().addTo(AppState.map);
}
/* ==========================================================================
2. Heatmap & Layer Rendering Engine
========================================================================== */
function updateHeatmap() {
if (!AppState.map) return;
const currentOffset = pollutionData.timelineOffsets[AppState.currentTimeStepIndex].key;
const pollutantKey = AppState.activePollutant;
const pollInfo = pollutionData.pollutantTypes[pollutantKey] || pollutionData.pollutantTypes.aqi;
const allZones = [...pollutionData.zones, ...AppState.customZones];
const heatPoints = [];
// Clear existing markers
AppState.markersGroup.clearLayers();
allZones.forEach(zone => {
const fData = zone.forecasts[currentOffset] || zone.forecasts[0];
if (!fData) return;
const val = fData[pollutantKey] || fData.aqi || 100;
// Normalize intensity between 0.1 and 1.0 based on pollutant max threshold
const maxThresh = pollInfo.max || 500;
const intensity = Math.min(Math.max(val / maxThresh, 0.1), 1.0);
// Heat point tuple: [lat, lng, intensity]
heatPoints.push([zone.lat, zone.lng, intensity]);
// Create interactive pulsing map markers for high risk / emerging zones
const markerColor = getAQIColor(fData.aqi || 200);
const isEmerging = fData.status && fData.status.toLowerCase().includes("upcoming");
const customMarkerIcon = L.divIcon({
className: "custom-map-pin",
html: `
<div style="
position: relative;
width: 28px;
height: 28px;
background: ${markerColor};
border: 2px solid #ffffff;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
font-weight: 800;
font-size: 11px;
box-shadow: 0 0 16px ${markerColor};
cursor: pointer;
">
${Math.round(val)}
${isEmerging ? `<div class="pulse-ring" style="
position: absolute;
inset: -6px;
border: 2px solid ${markerColor};
border-radius: 50%;
animation: marker-pulse 1.8s infinite;
"></div>` : ""}
</div>
`,
iconSize: [28, 28],
iconAnchor: [14, 14]
});
const marker = L.marker([zone.lat, zone.lng], { icon: customMarkerIcon });
// Popup summary
const popupContent = `
<div style="padding: 4px;">
<div style="font-size: 14px; font-weight: 700; color: #fff;">${zone.name}</div>
<div style="font-size: 11px; color: #94a3b8; margin-bottom: 8px;">${zone.category}</div>
<div style="display: flex; align-items: center; justify-content: space-between; gap: 12px; background: rgba(255,255,255,0.06); padding: 8px; border-radius: 6px;">
<div>
<div style="font-size: 10px; color: #64748b; text-transform: uppercase;">${pollInfo.name}</div>
<div style="font-size: 18px; font-weight: 800; color: ${markerColor};">${val} ${pollInfo.unit}</div>
</div>
<div style="text-align: right;">
<div style="font-size: 10px; color: #64748b;">Risk Level</div>
<div style="font-size: 12px; font-weight: 700; color: ${markerColor};">${fData.riskLevel || "High"}</div>
</div>
</div>
<div style="margin-top: 8px; font-size: 11px; color: #cbd5e1;">
<i class="fa-solid fa-triangle-exclamation" style="color: #f59e0b;"></i> ${fData.status || "Observed Sensor Data"}
</div>
</div>
`;
marker.bindPopup(popupContent);
marker.on("click", () => selectZone(zone));
AppState.markersGroup.addLayer(marker);
});
// Remove existing heatLayer if present
if (AppState.heatLayer) {
AppState.map.removeLayer(AppState.heatLayer);
}
// Create new Leaflet Heat layer with smooth atmospheric gradient
AppState.heatLayer = L.heatLayer(heatPoints, {
radius: AppState.heatRadius,
blur: AppState.heatBlur,
maxZoom: 10,
max: 1.0,
minOpacity: AppState.heatOpacity,
gradient: {
0.15: "#10B981", // Good Green
0.35: "#F59E0B", // Moderate Amber
0.55: "#F97316", // Unhealthy Orange
0.75: "#EF4444", // Severe Red
0.90: "#8B5CF6", // Purple
1.00: "#881337" // Hazardous Maroon
}
}).addTo(AppState.map);
}
/* ==========================================================================
3. Sidebar Intelligence & Selected Zone Logic
========================================================================== */
function selectZone(zone) {
if (!zone) return;
AppState.selectedZone = zone;
const currentOffset = pollutionData.timelineOffsets[AppState.currentTimeStepIndex].key;
const fData = zone.forecasts[currentOffset] || zone.forecasts[0];
const pollutantKey = AppState.activePollutant;
const val = fData[pollutantKey] || fData.aqi;
const color = getAQIColor(fData.aqi);
// Update DOM Elements
document.getElementById("active-zone-name").innerText = zone.name;
document.getElementById("active-zone-category").innerText = zone.category;
const aqiBadge = document.getElementById("active-aqi-badge");
aqiBadge.innerText = Math.round(val);
aqiBadge.style.backgroundColor = color;
aqiBadge.style.color = "#ffffff";
const riskEl = document.getElementById("active-risk-level");
riskEl.innerText = fData.riskLevel || getRiskCategoryLabel(fData.aqi);
riskEl.style.color = color;
document.getElementById("active-growth-rate").innerText = fData.growthRate || "+0.0%";
document.getElementById("active-primary-source").innerText = zone.primarySource || "Mixed Urban";
document.getElementById("active-wind-info").innerText = `${fData.windDir || 'N/A'} @ ${fData.windSpeed || '10 km/h'}`;
// Update Trend Chart
updateForecastChart(zone);
// Smooth fly map to selected zone
if (AppState.map) {
AppState.map.flyTo([zone.lat, zone.lng], 8, { duration: 1.2 });
}
}
function updateForecastChart(zone) {
const ctx = document.getElementById("forecast-trend-chart").getContext("2d");
const currentOffset = pollutionData.timelineOffsets[AppState.currentTimeStepIndex].key;
const labels = pollutionData.timelineOffsets.map(t => t.shortLabel);
const dataPoints = pollutionData.timelineOffsets.map(t => {
const f = zone.forecasts[t.key] || zone.forecasts[0];
return f[AppState.activePollutant] || f.aqi;
});
if (AppState.trendChart) {
AppState.trendChart.destroy();
}
// Create neon gradient fill for Chart.js
const gradient = ctx.createLinearGradient(0, 0, 0, 160);
gradient.addColorStop(0, "rgba(6, 182, 212, 0.4)");
gradient.addColorStop(1, "rgba(6, 182, 212, 0.0)");
AppState.trendChart = new Chart(ctx, {
type: "line",
data: {
labels: labels,
datasets: [{
label: AppState.activePollutant.toUpperCase(),
data: dataPoints,
borderColor: "#06b6d4",
borderWidth: 3,
pointBackgroundColor: labels.map((l, idx) => {
return pollutionData.timelineOffsets[idx].key === currentOffset ? "#ffffff" : "#06b6d4";
}),
pointRadius: labels.map((l, idx) => {
return pollutionData.timelineOffsets[idx].key === currentOffset ? 6 : 3;
}),
fill: true,
backgroundColor: gradient,
tension: 0.35
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: false },
tooltip: {
backgroundColor: "#0d1321",
borderColor: "rgba(255,255,255,0.15)",
borderWidth: 1,
titleColor: "#fff",
bodyColor: "#06b6d4"
}
},
scales: {
x: {
grid: { color: "rgba(255, 255, 255, 0.05)" },
ticks: { color: "#64748b", font: { size: 10 } }
},
y: {
grid: { color: "rgba(255, 255, 255, 0.05)" },
ticks: { color: "#64748b", font: { size: 10 } }
}
}
}
});
}
function renderHotspotsLeaderboard() {
const container = document.getElementById("upcoming-hotspots-list");
container.innerHTML = "";
const currentOffset = pollutionData.timelineOffsets[AppState.currentTimeStepIndex].key;
const allZones = [...pollutionData.zones, ...AppState.customZones];
// Sort zones by AQI descending at current time step
const sorted = [...allZones].sort((a, b) => {
const valA = (a.forecasts[currentOffset] || a.forecasts[0]).aqi;
const valB = (b.forecasts[currentOffset] || b.forecasts[0]).aqi;
return valB - valA;
});
sorted.slice(0, 6).forEach(zone => {
const fData = zone.forecasts[currentOffset] || zone.forecasts[0];
const val = fData[AppState.activePollutant] || fData.aqi;
const color = getAQIColor(fData.aqi);
const item = document.createElement("div");
item.className = "hotspot-item";
item.innerHTML = `
<div class="hotspot-info">
<div class="hotspot-name">${zone.name}</div>
<div class="hotspot-sub">${fData.status || zone.category}</div>
</div>
<div class="hotspot-pill" style="background: ${color}22; color: ${color}; border: 1px solid ${color}44;">
${Math.round(val)} <span style="font-size: 9px;">${fData.growthRate ? fData.growthRate : ''}</span>
</div>
`;
item.addEventListener("click", () => selectZone(zone));
container.appendChild(item);
});
}
/* ==========================================================================
4. Controls & Listeners
========================================================================== */
function initPollutantSelectors() {
const btns = document.querySelectorAll("#pollutant-selector-grid .pollutant-btn");
btns.forEach(btn => {
btn.addEventListener("click", () => {
btns.forEach(b => b.classList.remove("active"));
btn.classList.add("active");
AppState.activePollutant = btn.getAttribute("data-pollutant");
updateAllViews();
});
});
}
function initLayerControls() {
const blurSlider = document.getElementById("slider-heat-blur");
const radiusSlider = document.getElementById("slider-heat-radius");
const opacitySlider = document.getElementById("slider-heat-opacity");
blurSlider.addEventListener("input", (e) => {
AppState.heatBlur = parseInt(e.target.value);
updateHeatmap();
});
radiusSlider.addEventListener("input", (e) => {
AppState.heatRadius = parseInt(e.target.value);
updateHeatmap();
});
opacitySlider.addEventListener("input", (e) => {
AppState.heatOpacity = parseFloat(e.target.value);
updateHeatmap();
});
// Toggle Sidebar Minimize
const toggleBtn = document.getElementById("btn-toggle-sidebar");
const sidebar = document.querySelector(".analytics-sidebar");
let isMinimized = false;
toggleBtn.addEventListener("click", () => {
isMinimized = !isMinimized;
if (isMinimized) {
sidebar.style.transform = "translateX(-360px)";
toggleBtn.innerHTML = '<i class="fa-solid fa-chevron-right"></i>';
} else {
sidebar.style.transform = "translateX(0)";
toggleBtn.innerHTML = '<i class="fa-solid fa-chevron-left"></i>';
}
});
}
function initTimelineControls() {
const playBtn = document.getElementById("btn-play-timeline");
const playIcon = document.getElementById("play-icon");
const slider = document.getElementById("timeline-slider-input");
const stepElements = document.querySelectorAll("#timeline-steps-container .timeline-step");
function setTimeStepIndex(idx) {
AppState.currentTimeStepIndex = idx;
slider.value = idx;
stepElements.forEach((el, i) => {
if (i === idx) el.classList.add("active");
else el.classList.remove("active");
});
const info = pollutionData.timelineOffsets[idx];
document.getElementById("current-timeline-label").innerText = info.label;
const badge = document.getElementById("forecast-mode-badge");
if (idx === 0) {
badge.innerHTML = '<i class="fa-solid fa-satellite-dish"></i> Real-Time Mode';
badge.style.background = 'rgba(6, 182, 212, 0.12)';
badge.style.color = 'var(--accent-cyan)';
} else {
badge.innerHTML = `<i class="fa-solid fa-bolt" style="color: #f59e0b;"></i> ${info.shortLabel} Forecast`;
badge.style.background = 'rgba(245, 158, 11, 0.15)';
badge.style.color = '#f59e0b';
}
updateAllViews();
}
slider.addEventListener("input", (e) => {
setTimeStepIndex(parseInt(e.target.value));
});
stepElements.forEach((el, idx) => {
el.addEventListener("click", () => setTimeStepIndex(idx));
});
playBtn.addEventListener("click", () => {
AppState.isPlaying = !AppState.isPlaying;
if (AppState.isPlaying) {
playIcon.className = "fa-solid fa-pause";
AppState.playInterval = setInterval(() => {
let nextIdx = (AppState.currentTimeStepIndex + 1) % pollutionData.timelineOffsets.length;
setTimeStepIndex(nextIdx);
}, 2400);
} else {
playIcon.className = "fa-solid fa-play";
clearInterval(AppState.playInterval);
}
});
}
function initSearch() {
const input = document.getElementById("search-input");
input.addEventListener("keyup", (e) => {
const query = e.target.value.toLowerCase().trim();
if (query.length < 2) return;
const matched = pollutionData.zones.find(z =>
z.name.toLowerCase().includes(query) ||
z.country.toLowerCase().includes(query) ||
z.category.toLowerCase().includes(query)
);
if (matched && e.key === "Enter") {
selectZone(matched);
}
});
}
function initModalUploader() {
const modal = document.getElementById("upload-modal");
const openBtn = document.getElementById("btn-upload-modal");
const closeBtn = document.getElementById("btn-close-modal");
const cancelBtn = document.getElementById("btn-cancel-modal");
const dropzone = document.getElementById("dropzone");
const fileInput = document.getElementById("file-input-element");
const submitBtn = document.getElementById("btn-submit-upload");
openBtn.addEventListener("click", () => modal.classList.add("active"));
closeBtn.addEventListener("click", () => modal.classList.remove("active"));
cancelBtn.addEventListener("click", () => modal.classList.remove("active"));
dropzone.addEventListener("click", () => fileInput.click());
fileInput.addEventListener("change", (e) => {
if (e.target.files.length > 0) {
const name = e.target.files[0].name;
dropzone.querySelector("div").innerText = `Selected File: ${name}`;
}
});
submitBtn.addEventListener("click", () => {
if (fileInput.files.length === 0) {
alert("Please choose a valid CSV or JSON file first.");
return;
}
const reader = new FileReader();
reader.onload = function(evt) {
try {
const text = evt.target.result;
parseAndLoadCustomData(text);
modal.classList.remove("active");
alert("Custom dataset loaded successfully into AeroPulse!");
} catch (err) {
alert("Failed to parse file. Please verify CSV/JSON format.");
}
};
reader.readAsText(fileInput.files[0]);
});
}
function parseAndLoadCustomData(content) {
// Simple CSV / JSON parser for custom user uploads
if (content.trim().startsWith("[")) {
const parsed = JSON.parse(content);
AppState.customZones = parsed;
} else {
const lines = content.split("\n").filter(l => l.trim().length > 0);
const headers = lines[0].split(",").map(h => h.trim().toLowerCase());
const latIdx = headers.indexOf("lat");
const lngIdx = headers.indexOf("lng");
const nameIdx = headers.indexOf("location_name") !== -1 ? headers.indexOf("location_name") : headers.indexOf("name");
const aqiIdx = headers.indexOf("aqi");
const importedZones = [];
for (let i = 1; i < lines.length; i++) {
const parts = lines[i].split(",");
if (parts.length > Math.max(latIdx, lngIdx, aqiIdx)) {
const lat = parseFloat(parts[latIdx]);
const lng = parseFloat(parts[lngIdx]);
const aqi = parseFloat(parts[aqiIdx]) || 150;
const name = nameIdx !== -1 ? parts[nameIdx] : `Sensor Node ${i}`;
if (!isNaN(lat) && !isNaN(lng)) {
importedZones.push({
id: `custom-${i}`,
name: name,
country: "User Dataset",
category: "Custom Sensor Upload",
lat: lat,
lng: lng,
primarySource: "Custom Field Monitor",
forecasts: {
0: { aqi: aqi, riskLevel: getRiskCategoryLabel(aqi), status: "User Uploaded Sensor" },
6: { aqi: aqi * 1.05, riskLevel: getRiskCategoryLabel(aqi * 1.05), status: "Projected Trend" }
}
});
}
}
}
if (importedZones.length > 0) {
AppState.customZones = importedZones;
}
}
updateAllViews();
}
function initExportEngine() {
const exportBtn = document.getElementById("btn-export-report");
exportBtn.addEventListener("click", () => {
const currentOffset = pollutionData.timelineOffsets[AppState.currentTimeStepIndex].key;
const summaryData = pollutionData.zones.map(z => {
const f = z.forecasts[currentOffset] || z.forecasts[0];
return {
zone: z.name,
country: z.country,
category: z.category,
timeline: `+${currentOffset}h`,
aqi: f.aqi,
risk: f.riskLevel,
growth: f.growthRate,
source: z.primarySource
};
});
const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(summaryData, null, 2));
const downloadAnchor = document.createElement("a");
downloadAnchor.setAttribute("href", dataStr);
downloadAnchor.setAttribute("download", `AeroPulse_Pollution_Report_${Date.now()}.json`);
document.body.appendChild(downloadAnchor);
downloadAnchor.click();
downloadAnchor.remove();
});
}
function updateAllViews() {
updateHeatmap();
renderHotspotsLeaderboard();
if (AppState.selectedZone) {
selectZone(AppState.selectedZone);
}
}