Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
636 lines (559 loc) · 21.3 KB
/
Copy pathscript.js
File metadata and controls
636 lines (559 loc) · 21.3 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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
// Global variables
let map;
let weatherLayer;
let weatherData;
let chatMessages = [];
let isTyping = false;
let currentTimeSlot = 0;
let timeSlots = [];
let weatherTimeData = [];
let isPlaying = false;
let animationInterval = null;
// Weather classification colors
const weatherColors = {
'cerah': '#FFD700', // Gold
'berawan': '#808080', // Gray
'hujan_ringan': '#00FF00', // Green
'hujan_sedang': '#FFFF00', // Yellow
'hujan_lebat': '#FF0000' // Red
};
// Weather icons
const weatherIcons = {
'cerah': '☀️',
'berawan': '⛅',
'hujan_ringan': '🌦️',
'hujan_sedang': '🌧️',
'hujan_lebat': '⛈️'
};
// Initialize the application
document.addEventListener('DOMContentLoaded', function() {
initializeMap();
generateTimeSlots();
loadWeatherData();
initializeChat();
setupEventListeners();
initializeTimeSlider();
});
// Initialize Leaflet map
function initializeMap() {
// Center on Jakarta region
map = L.map('map').setView([-6.2, 106.8], 10);
// Add OpenStreetMap tiles
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
// Initialize weather layer
weatherLayer = L.layerGroup().addTo(map);
}
// Generate time slots for 1 hour (6 slots of 10 minutes each)
function generateTimeSlots() {
const now = new Date();
timeSlots = [];
for (let i = 0; i < 6; i++) {
const time = new Date(now.getTime() + (i * 10 * 60 * 1000)); // Add 10 minutes for each slot
timeSlots.push({
index: i,
time: time,
label: time.toLocaleTimeString('id-ID', {
hour: '2-digit',
minute: '2-digit',
hour12: false
})
});
}
}
// Load weather data from multiple GeoJSON files
async function loadWeatherData() {
try {
// Load all city GeoJSON files
const cities = ['jakarta', 'bogor', 'bekasi', 'depok', 'tangerang'];
const allFeatures = [];
for (const city of cities) {
try {
const response = await fetch(`data/${city}.geojson`);
const cityData = await response.json();
allFeatures.push(...cityData.features);
} catch (error) {
console.error(`Error loading ${city}.geojson:`, error);
}
}
// Combine all features into one GeoJSON
weatherData = {
type: "FeatureCollection",
features: allFeatures
};
generateWeatherTimeData();
displayWeatherOnMap();
} catch (error) {
console.error('Error loading weather data:', error);
showNotification('Gagal memuat data cuaca', 'error');
}
}
// Generate weather data for different time slots with realistic spatial patterns
function generateWeatherTimeData() {
if (!weatherData) return;
weatherTimeData = [];
// Define spatial patterns for rain progression
const rainPatterns = [
// Slot 0: Starting with scattered clouds
{
'Jakarta Pusat': 'berawan',
'Jakarta Utara': 'berawan',
'Jakarta Selatan': 'berawan',
'Jakarta Timur': 'cerah',
'Jakarta Barat': 'berawan',
'Bogor': 'berawan',
'Bekasi': 'berawan',
'Depok': 'berawan',
'Tangerang': 'berawan',
'Tangerang Selatan': 'berawan'
},
// Slot 1: Light rain starts in Bogor and spreads
{
'Jakarta Pusat': 'berawan',
'Jakarta Utara': 'hujan_ringan',
'Jakarta Selatan': 'berawan',
'Jakarta Timur': 'cerah',
'Jakarta Barat': 'berawan',
'Bogor': 'hujan_ringan',
'Bekasi': 'berawan',
'Depok': 'hujan_ringan',
'Tangerang': 'berawan',
'Tangerang Selatan': 'berawan'
},
// Slot 2: Rain spreads to more areas
{
'Jakarta Pusat': 'hujan_ringan',
'Jakarta Utara': 'hujan_ringan',
'Jakarta Selatan': 'hujan_ringan',
'Jakarta Timur': 'berawan',
'Jakarta Barat': 'hujan_ringan',
'Bogor': 'hujan_sedang',
'Bekasi': 'hujan_ringan',
'Depok': 'hujan_sedang',
'Tangerang': 'hujan_ringan',
'Tangerang Selatan': 'hujan_ringan'
},
// Slot 3: Moderate rain in most areas
{
'Jakarta Pusat': 'hujan_sedang',
'Jakarta Utara': 'hujan_sedang',
'Jakarta Selatan': 'hujan_sedang',
'Jakarta Timur': 'hujan_ringan',
'Jakarta Barat': 'hujan_sedang',
'Bogor': 'hujan_lebat',
'Bekasi': 'hujan_sedang',
'Depok': 'hujan_lebat',
'Tangerang': 'hujan_sedang',
'Tangerang Selatan': 'hujan_sedang'
},
// Slot 4: Heavy rain in most areas
{
'Jakarta Pusat': 'hujan_lebat',
'Jakarta Utara': 'hujan_lebat',
'Jakarta Selatan': 'hujan_sedang',
'Jakarta Timur': 'hujan_sedang',
'Jakarta Barat': 'hujan_lebat',
'Bogor': 'hujan_lebat',
'Bekasi': 'hujan_lebat',
'Depok': 'hujan_lebat',
'Tangerang': 'hujan_lebat',
'Tangerang Selatan': 'hujan_sedang'
},
// Slot 5: Peak rainfall
{
'Jakarta Pusat': 'hujan_lebat',
'Jakarta Utara': 'hujan_lebat',
'Jakarta Selatan': 'hujan_lebat',
'Jakarta Timur': 'hujan_lebat',
'Jakarta Barat': 'hujan_lebat',
'Bogor': 'hujan_lebat',
'Bekasi': 'hujan_lebat',
'Depok': 'hujan_lebat',
'Tangerang': 'hujan_lebat',
'Tangerang Selatan': 'hujan_lebat'
}
];
for (let slot = 0; slot < 6; slot++) {
const timeData = JSON.parse(JSON.stringify(weatherData)); // Deep copy
const pattern = rainPatterns[slot];
timeData.features.forEach(feature => {
const props = feature.properties;
const weatherType = pattern[props.name] || 'berawan';
// Set weather based on pattern
props.weather = weatherType;
// Set appropriate values based on weather type
switch (weatherType) {
case 'cerah':
props.temperature = 32 + Math.floor(Math.random() * 3);
props.humidity = 65 + Math.floor(Math.random() * 10);
props.wind_speed = 8 + Math.floor(Math.random() * 5);
props.pressure = 1015 + Math.floor(Math.random() * 3);
props.description = 'Cerah dengan sinar matahari penuh';
break;
case 'berawan':
props.temperature = 30 + Math.floor(Math.random() * 3);
props.humidity = 75 + Math.floor(Math.random() * 10);
props.wind_speed = 10 + Math.floor(Math.random() * 5);
props.pressure = 1013 + Math.floor(Math.random() * 3);
props.description = 'Berawan dengan awan menutupi sebagian langit';
break;
case 'hujan_ringan':
props.temperature = 28 + Math.floor(Math.random() * 3);
props.humidity = 80 + Math.floor(Math.random() * 8);
props.wind_speed = 12 + Math.floor(Math.random() * 5);
props.pressure = 1010 + Math.floor(Math.random() * 3);
props.description = 'Hujan ringan dengan intensitas rendah';
break;
case 'hujan_sedang':
props.temperature = 26 + Math.floor(Math.random() * 3);
props.humidity = 85 + Math.floor(Math.random() * 8);
props.wind_speed = 15 + Math.floor(Math.random() * 5);
props.pressure = 1008 + Math.floor(Math.random() * 3);
props.description = 'Hujan sedang dengan intensitas sedang';
break;
case 'hujan_lebat':
props.temperature = 24 + Math.floor(Math.random() * 3);
props.humidity = 90 + Math.floor(Math.random() * 5);
props.wind_speed = 18 + Math.floor(Math.random() * 7);
props.pressure = 1005 + Math.floor(Math.random() * 3);
props.description = 'Hujan lebat dengan intensitas tinggi';
break;
}
});
weatherTimeData.push(timeData);
}
}
// Display weather data on map
function displayWeatherOnMap() {
if (!weatherTimeData || weatherTimeData.length === 0) {
console.log('No weather time data available');
return;
}
// Clear existing layers
weatherLayer.clearLayers();
const currentData = weatherTimeData[currentTimeSlot];
if (!currentData || !currentData.features) {
console.log('No features in current data');
return;
}
currentData.features.forEach((feature) => {
const properties = feature.properties;
const coordinates = feature.geometry.coordinates[0];
// Create polygon with weather-based styling
const polygon = L.polygon(coordinates, {
color: weatherColors[properties.weather] || '#666',
fillColor: weatherColors[properties.weather] || '#666',
fillOpacity: 0.7,
weight: 2
});
// Add popup with weather information
const popupContent = `
<div class="weather-popup">
<h3>${properties.name}</h3>
<div class="weather-info">
<div class="weather-icon">${weatherIcons[properties.weather]}</div>
<div class="weather-details">
<p><strong>Waktu:</strong> ${timeSlots[currentTimeSlot].label}</p>
<p><strong>Suhu:</strong> ${properties.temperature}°C</p>
<p><strong>Kelembaban:</strong> ${properties.humidity}%</p>
<p><strong>Cuaca:</strong> ${properties.description}</p>
<p><strong>Kecepatan Angin:</strong> ${properties.wind_speed} km/h</p>
<p><strong>Tekanan:</strong> ${properties.pressure} hPa</p>
</div>
</div>
</div>
`;
polygon.bindPopup(popupContent);
// Add click event to show detailed weather info
polygon.on('click', function() {
showWeatherInfoPanel(properties);
});
weatherLayer.addLayer(polygon);
});
}
// Show weather info panel
function showWeatherInfoPanel(weatherInfo) {
const panel = document.getElementById('weatherInfoPanel');
const cityName = document.getElementById('selectedCity');
const content = document.getElementById('panelContent');
cityName.textContent = weatherInfo.name;
content.innerHTML = `
<div class="weather-detail">
<div class="weather-main">
<div class="weather-icon-large">${weatherIcons[weatherInfo.weather]}</div>
<div class="weather-temp">${weatherInfo.temperature}°C</div>
</div>
<div class="weather-description">${weatherInfo.description}</div>
<div class="weather-stats">
<div class="stat-item">
<i class="fas fa-tint"></i>
<span>Kelembaban: ${weatherInfo.humidity}%</span>
</div>
<div class="stat-item">
<i class="fas fa-wind"></i>
<span>Angin: ${weatherInfo.wind_speed} km/h</span>
</div>
<div class="stat-item">
<i class="fas fa-thermometer-half"></i>
<span>Tekanan: ${weatherInfo.pressure} hPa</span>
</div>
</div>
</div>
`;
panel.classList.add('show');
}
// Initialize chat functionality
function initializeChat() {
const chatInput = document.getElementById('chatInput');
const sendButton = document.getElementById('sendButton');
const quickButtons = document.querySelectorAll('.quick-btn');
// Send message on Enter key
chatInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
});
// Send message on button click
sendButton.addEventListener('click', sendMessage);
// Quick question buttons
quickButtons.forEach(button => {
button.addEventListener('click', function() {
const question = this.getAttribute('data-question');
chatInput.value = question;
sendMessage();
});
});
}
// Setup event listeners
function setupEventListeners() {
// Close weather info panel
document.getElementById('closePanel').addEventListener('click', function() {
document.getElementById('weatherInfoPanel').classList.remove('show');
});
// Close panel when clicking outside
document.addEventListener('click', function(e) {
const panel = document.getElementById('weatherInfoPanel');
if (!panel.contains(e.target) && !e.target.closest('.weather-popup')) {
panel.classList.remove('show');
}
});
}
// Send message to AI
async function sendMessage() {
const chatInput = document.getElementById('chatInput');
const message = chatInput.value.trim();
if (!message || isTyping) return;
// Add user message to chat
addMessageToChat(message, 'user');
chatInput.value = '';
// Show loading
showLoading(true);
isTyping = true;
try {
// Get AI response
const response = await getAIResponse(message);
addMessageToChat(response, 'bot');
} catch (error) {
console.error('Error getting AI response:', error);
addMessageToChat('Maaf, terjadi kesalahan saat memproses pertanyaan Anda. Silakan coba lagi.', 'bot');
} finally {
showLoading(false);
isTyping = false;
}
}
// Add message to chat
function addMessageToChat(message, sender) {
const chatMessages = document.getElementById('chatMessages');
const messageDiv = document.createElement('div');
messageDiv.className = `message ${sender}-message`;
const avatar = sender === 'user' ?
'<i class="fas fa-user"></i>' :
'<i class="fas fa-robot"></i>';
messageDiv.innerHTML = `
<div class="message-avatar">
${avatar}
</div>
<div class="message-content">
<p>${message}</p>
</div>
`;
chatMessages.appendChild(messageDiv);
chatMessages.scrollTop = chatMessages.scrollHeight;
}
// Get AI response from backend
async function getAIResponse(message) {
const response = await fetch('/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: message,
weatherData: weatherData
})
});
if (!response.ok) {
throw new Error('Failed to get AI response');
}
const data = await response.json();
return data.response;
}
// Show/hide loading overlay
function showLoading(show) {
const overlay = document.getElementById('loadingOverlay');
if (show) {
overlay.classList.add('show');
} else {
overlay.classList.remove('show');
}
}
// Show notification
function showNotification(message, type = 'info') {
// Create notification element
const notification = document.createElement('div');
notification.className = `notification ${type}`;
notification.innerHTML = `
<i class="fas fa-${type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
<span>${message}</span>
`;
document.body.appendChild(notification);
// Show notification
setTimeout(() => notification.classList.add('show'), 100);
// Remove notification after 3 seconds
setTimeout(() => {
notification.classList.remove('show');
setTimeout(() => document.body.removeChild(notification), 300);
}, 3000);
}
// Update weather data (simulate real-time updates)
function updateWeatherData() {
if (!weatherData) return;
// Simulate weather changes
weatherData.features.forEach(feature => {
const props = feature.properties;
// Random weather changes
if (Math.random() < 0.1) { // 10% chance of change
const weathers = ['cerah', 'berawan', 'hujan_ringan', 'hujan_lebat'];
props.weather = weathers[Math.floor(Math.random() * weathers.length)];
props.temperature += Math.floor(Math.random() * 3) - 1; // ±1°C
props.humidity += Math.floor(Math.random() * 5) - 2; // ±2%
}
});
// Refresh map display
displayWeatherOnMap();
}
// Initialize time slider
function initializeTimeSlider() {
const slider = document.getElementById('timeSlider');
const timeDisplay = document.getElementById('timeDisplay');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
const playBtn = document.getElementById('playBtn');
if (slider && timeDisplay) {
slider.min = 0;
slider.max = 5;
slider.value = 0;
// Update time display
updateTimeDisplay();
updateButtonStates();
// Add event listener for slider change
slider.addEventListener('input', function() {
currentTimeSlot = parseInt(this.value);
updateTimeDisplay();
updateButtonStates();
displayWeatherOnMap();
});
// Previous button
if (prevBtn) {
prevBtn.addEventListener('click', function() {
if (currentTimeSlot > 0) {
currentTimeSlot--;
slider.value = currentTimeSlot;
updateTimeDisplay();
updateButtonStates();
displayWeatherOnMap();
}
});
}
// Next button
if (nextBtn) {
nextBtn.addEventListener('click', function() {
if (currentTimeSlot < 5) {
currentTimeSlot++;
slider.value = currentTimeSlot;
updateTimeDisplay();
updateButtonStates();
displayWeatherOnMap();
}
});
}
// Play/Pause button
if (playBtn) {
playBtn.addEventListener('click', function() {
toggleAnimation();
});
}
}
}
// Update time display
function updateTimeDisplay() {
const timeDisplay = document.getElementById('timeDisplay');
if (timeDisplay && timeSlots[currentTimeSlot]) {
timeDisplay.textContent = `Waktu: ${timeSlots[currentTimeSlot].label}`;
}
}
// Update button states
function updateButtonStates() {
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
if (prevBtn) {
prevBtn.disabled = currentTimeSlot === 0;
}
if (nextBtn) {
nextBtn.disabled = currentTimeSlot === 5;
}
}
// Toggle animation
function toggleAnimation() {
const playBtn = document.getElementById('playBtn');
const playIcon = playBtn.querySelector('i');
if (isPlaying) {
// Stop animation
clearInterval(animationInterval);
isPlaying = false;
playIcon.className = 'fas fa-play';
playBtn.classList.remove('playing');
playBtn.title = 'Play Animation';
} else {
// Start animation
isPlaying = true;
playIcon.className = 'fas fa-pause';
playBtn.classList.add('playing');
playBtn.title = 'Pause Animation';
animationInterval = setInterval(() => {
if (currentTimeSlot < 5) {
currentTimeSlot++;
} else {
currentTimeSlot = 0; // Loop back to start
}
const slider = document.getElementById('timeSlider');
slider.value = currentTimeSlot;
updateTimeDisplay();
updateButtonStates();
displayWeatherOnMap();
}, 1000); // 1 second per frame
}
}
// Update weather every 30 seconds
setInterval(updateWeatherData, 30000);
// Export functions for testing
window.weatherApp = {
initializeMap,
loadWeatherData,
displayWeatherOnMap,
sendMessage,
addMessageToChat,
getAIResponse
};