-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapUtils.js
More file actions
247 lines (215 loc) · 7.64 KB
/
mapUtils.js
File metadata and controls
247 lines (215 loc) · 7.64 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
import L from 'leaflet';
let mapInstance = null;
let radarLayer = null;
let animationTimer = null;
let timestamps = []; // Holds available times from RainViewer
let currentFrameIndex = 0;
let isPlaying = true;
let currentLayerType = 'precip'; // 'precip' or 'clouds'
let cloudsLayer = null;
// DOM
let playBtn, timeSlider, timeDisplay, btnPrecip, btnClouds, playbackControls, radarLegend;
/**
* Initialize Leaflet Map
* @param {HTMLElement} containerElement
* @param {number} lat
* @param {number} lon
*/
export function initMap(containerElement, lat, lon) {
if (mapInstance) {
mapInstance.remove(); // Cleanup previous instance if any
}
mapInstance = L.map(containerElement, {
center: [lat, lon],
zoom: 8,
zoomControl: false // Custom or cleaner UI
});
// Add OpenStreetMap Base Layer
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors',
maxZoom: 18,
}).addTo(mapInstance);
// Reposition zoom control
L.control.zoom({
position: 'bottomright'
}).addTo(mapInstance);
// Get DOM elements
playBtn = document.getElementById('map-play-btn');
timeSlider = document.getElementById('map-slider');
timeDisplay = document.getElementById('map-time');
btnPrecip = document.getElementById('btn-layer-precip');
btnClouds = document.getElementById('btn-layer-clouds');
playbackControls = document.getElementById('radar-playback');
radarLegend = document.getElementById('radar-legend');
if (playBtn) {
playBtn.onclick = () => {
if (currentLayerType !== 'precip') return;
isPlaying = !isPlaying;
playBtn.innerHTML = isPlaying ? '<i class="ri-pause-fill"></i>' : '<i class="ri-play-fill"></i>';
if (isPlaying) {
startAnimationLoop();
} else {
clearInterval(animationTimer);
}
};
}
if (timeSlider) {
timeSlider.oninput = (e) => {
if (currentLayerType !== 'precip') return;
if (isPlaying) {
isPlaying = false;
playBtn.innerHTML = '<i class="ri-play-fill"></i>';
clearInterval(animationTimer);
}
currentFrameIndex = parseInt(e.target.value, 10);
showFrame(currentFrameIndex);
};
}
if (btnPrecip && btnClouds) {
btnPrecip.onclick = () => switchLayer('precip');
btnClouds.onclick = () => switchLayer('clouds');
}
// Initial Radar Load
startRadarAnimation();
}
/**
* Update Map Center
* @param {number} lat
* @param {number} lon
*/
export function updateMap(lat, lon) {
if (mapInstance) {
mapInstance.setView([lat, lon], 8);
}
}
/**
* Fix Resize issues (call when tab becomes visible)
*/
export function resizeMap() {
if (mapInstance) {
mapInstance.invalidateSize();
}
}
/**
* Start RainViewer Overlay Animation
*/
export function startRadarAnimation() {
fetch('https://api.rainviewer.com/public/weather-maps.json')
.then(res => res.json())
.then(data => {
if (data.radar && data.radar.past) {
timestamps = data.radar.past;
if (timestamps.length > 0) {
if (timeSlider) {
timeSlider.max = timestamps.length - 1;
timeSlider.value = 0;
}
playAnimation();
}
}
})
.catch(err => console.error("RainViewer API Error:", err));
}
function switchLayer(type) {
if (type === currentLayerType) return;
currentLayerType = type;
if (type === 'clouds') {
// Activate Cloud UI
if (btnClouds) btnClouds.classList.add('active');
if (btnPrecip) btnPrecip.classList.remove('active');
if (playbackControls) playbackControls.style.display = 'none';
if (radarLegend) radarLegend.style.display = 'none';
// Stop radar animation
isPlaying = false;
clearInterval(animationTimer);
if (playBtn) playBtn.innerHTML = '<i class="ri-play-fill"></i>';
// Remove radar layer
if (radarLayer && mapInstance.hasLayer(radarLayer)) {
mapInstance.removeLayer(radarLayer);
}
// Add clouds layer if not already added
if (!cloudsLayer) {
// Fetch configuration dynamically so the app is deployment ready without needing a local build
fetch('/api/config')
.then(res => res.json())
.then(config => {
const apiKey = config.owmKey;
if (!apiKey) {
console.warn("OpenWeatherMap API key is missing. Cloud tiles will not load.");
return;
}
cloudsLayer = L.tileLayer(`https://tile.openweathermap.org/map/clouds_new/{z}/{x}/{y}.png?appid=${apiKey}`, {
opacity: 0.8,
zIndex: 100,
maxNativeZoom: 18
});
// Only add if the user hasn't quickly toggled back to precip
if (currentLayerType === 'clouds' && !mapInstance.hasLayer(cloudsLayer)) {
cloudsLayer.addTo(mapInstance);
}
})
.catch(err => {
console.error("Failed to fetch OWM configuration:", err);
});
} else {
if (!mapInstance.hasLayer(cloudsLayer)) {
cloudsLayer.addTo(mapInstance);
}
}
} else if (type === 'precip') {
// Activate Precip UI
if (btnPrecip) btnPrecip.classList.add('active');
if (btnClouds) btnClouds.classList.remove('active');
if (playbackControls) playbackControls.style.display = 'flex';
if (radarLegend) radarLegend.style.display = 'block';
// Remove clouds layer
if (cloudsLayer && mapInstance.hasLayer(cloudsLayer)) {
mapInstance.removeLayer(cloudsLayer);
}
// Restart radar animation
playAnimation();
}
}
function showFrame(index) {
if (!mapInstance || timestamps.length === 0 || currentLayerType !== 'precip') return;
// Cache the old layer to prevent flickering during load
const oldLayer = radarLayer;
const tsObj = timestamps[index];
const ts = tsObj.time;
const path = tsObj.path;
radarLayer = L.tileLayer(`https://tilecache.rainviewer.com${path}/256/{z}/{x}/{y}/4/1_1.png`, {
opacity: 0.7,
zIndex: 100,
maxNativeZoom: 7
}).addTo(mapInstance);
// Remove old layer after slight delay
if (oldLayer) {
setTimeout(() => {
if (mapInstance.hasLayer(oldLayer)) {
mapInstance.removeLayer(oldLayer);
}
}, 100);
}
// Update UI
if (timeSlider) {
timeSlider.value = index;
}
if (timeDisplay) {
const d = new Date(ts * 1000);
timeDisplay.textContent = d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
}
}
function startAnimationLoop() {
if (animationTimer) clearInterval(animationTimer);
animationTimer = setInterval(() => {
currentFrameIndex = (currentFrameIndex + 1) % timestamps.length;
showFrame(currentFrameIndex);
}, 1000);
}
function playAnimation() {
currentFrameIndex = 0;
showFrame(currentFrameIndex);
isPlaying = true;
if (playBtn) playBtn.innerHTML = '<i class="ri-pause-fill"></i>';
startAnimationLoop();
}