-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
772 lines (679 loc) · 28.5 KB
/
Copy pathscript.js
File metadata and controls
772 lines (679 loc) · 28.5 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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
// ===== CONFIG =====
const OPENWEATHER_API_KEY = " ";
const OPENWEATHER_URL = "https://api.openweathermap.org/data/2.5/weather";
// Location coordinates for Uttarakhand and major cities
const locationCoords = {
'Dehradun': [30.3165, 78.0322],
'Haridwar': [29.9457, 78.1642],
'Rishikesh': [30.0869, 78.2676],
'Mussoorie': [30.4598, 78.0664],
'Nainital': [29.3803, 79.4636],
'Almora': [29.5971, 79.6593],
'Pithoragarh': [29.5841, 80.2186],
'Uttarkashi': [30.7268, 78.4354],
'Chamoli': [30.4041, 79.3280],
'Rudraprayag': [30.2849, 78.9811],
'Pauri': [30.1497, 78.7814],
'Tehri': [30.3783, 78.4803],
'Bageshwar': [29.8389, 79.7708],
'Badrinath': [30.7433, 79.4938],
'Kedarnath': [30.7346, 79.0669],
'Gangotri': [30.9990, 78.9408],
'Yamunotri': [31.0117, 78.4500],
'Hemkund Sahib': [30.7268, 79.6593],
'Auli': [30.5276, 79.5665],
'Chopta': [30.4555, 79.0295],
'Lansdowne': [29.8372, 78.6869],
'Kausani': [29.8397, 79.6094],
'Ranikhet': [29.6436, 79.4322],
'Bhimtal': [29.3498, 79.4261],
'Sat Tal': [29.3850, 79.4700],
'Mukteshwar': [29.4779, 79.6425],
'Binsar': [29.6833, 79.7167],
'Chaukori': [29.8483, 80.0383],
'Abbott Mount': [29.4500, 79.4167],
'Kanatal': [30.4167, 78.3167],
'Dhanaulti': [30.4167, 78.2667],
'Chakrata': [30.7030, 77.8683],
'Joshimath': [30.5564, 79.5641],
'Valley of Flowers': [30.7268, 79.6593],
'Har Ki Dun': [31.1333, 78.1500],
'Govind Ghat': [30.7500, 79.6000],
'Ghangaria': [30.7500, 79.6167],
'Dayara Bugyal': [30.8833, 78.5167],
'Bedni Bugyal': [30.2167, 79.4667],
'Ali Bugyal': [30.2333, 79.4833],
'Kotdwar': [29.7467, 78.1667],
'Roorkee': [29.8543, 77.8880],
'Vikasnagar': [30.4667, 77.7667],
'Herbertpur': [30.4333, 77.7000],
'Clement Town': [30.2667, 78.0167],
'Selaqui': [30.3667, 77.9833],
'Doiwala': [30.1833, 78.0667],
'Ramnagar': [29.3975, 79.1289],
'Haldwani': [29.2183, 79.5130],
'Kathgodam': [29.2667, 79.5333],
'Tanakpur': [29.0667, 80.1167],
'Champawat': [29.3369, 80.0922],
'Lohaghat': [29.4000, 80.0833],
'Devprayag': [30.1469, 78.5985],
'Karnaprayag': [30.2669, 79.2247],
'Nandprayag': [30.3167, 79.3167],
'Vishnuprayag': [30.5667, 79.4667],
'Govindghat': [30.7500, 79.6000],
'Gauchar': [30.0167, 79.3167],
'Guptkashi': [30.5500, 78.9167],
'Ukhimath': [30.5167, 79.1500],
'Sari Village': [30.4833, 79.0167],
'Triyuginarayan': [30.5833, 78.9833],
'Mandal': [30.6000, 79.4500],
'Tungnath': [30.4667, 79.2167],
'Mana': [30.7667, 79.5000],
'Malari': [30.8833, 79.7333],
'Niti': [30.8833, 79.8333],
'Dharchula': [29.8500, 80.5333],
'Munsyari': [30.0667, 80.2333],
'Milam': [30.4167, 80.0833],
'Pindari': [30.1833, 80.0167],
'Kafni': [30.1667, 80.0000],
'Jim Corbett National Park': [29.5300, 78.7500],
'Rajaji National Park': [30.1167, 78.0667],
'Nanda Devi National Park': [30.6333, 79.7500],
'Gangotri National Park': [30.9167, 78.7500],
'Srinagar (Garhwal)': [30.2167, 78.7833],
'Gopeshwar': [30.4041, 79.3280],
'Chinyalisaur': [30.8500, 78.5500],
'Barkot': [30.8167, 78.2000],
'Purola': [30.9667, 78.1167],
'Mana Pass': [30.8333, 79.4833],
'Lipulekh Pass': [30.9333, 81.0500],
'Nathu La Pass': [30.7500, 80.5000],
'New Delhi': [28.6139, 77.2090],
'Mumbai': [19.0760, 72.8777],
'Kolkata': [22.5726, 88.3639],
'Chennai': [13.0827, 80.2707],
'Bangalore': [12.9716, 77.5946],
'Hyderabad': [17.3850, 78.4867],
'Pune': [18.5204, 73.8567],
'Ahmedabad': [23.0225, 72.5714],
'Jaipur': [26.9124, 75.7873],
'Lucknow': [26.8467, 80.9462],
'Kanpur': [26.4499, 80.3319],
'Agra': [27.1767, 78.0081],
'Varanasi': [25.3176, 82.9739],
'Chandigarh': [30.7333, 76.7794]
};
const allLocations = Object.keys(locationCoords);
// Fallback location data
const locationData = {
'Dehradun': { weather: { temp: 25, condition: 'Pleasant', icon: '🌤️', humidity: 70, wind: 12, visibility: 8, pressure: 1015 }, risk: 'low' },
'Haridwar': { weather: { temp: 28, condition: 'Sunny', icon: '☀️', humidity: 65, wind: 10, visibility: 10, pressure: 1012 }, risk: 'low' },
'Rishikesh': { weather: { temp: 26, condition: 'Clear', icon: '🌞', humidity: 68, wind: 8, visibility: 12, pressure: 1014 }, risk: 'low' },
'Mussoorie': { weather: { temp: 18, condition: 'Cool', icon: '🏔️', humidity: 75, wind: 15, visibility: 6, pressure: 1018 }, risk: 'medium' },
'Nainital': { weather: { temp: 20, condition: 'Pleasant', icon: '🌤️', humidity: 72, wind: 14, visibility: 9, pressure: 1016 }, risk: 'low' },
'Badrinath': { weather: { temp: 8, condition: 'Very Cold', icon: '❄️', humidity: 85, wind: 25, visibility: 4, pressure: 1022 }, risk: 'high' },
'Kedarnath': { weather: { temp: 5, condition: 'Extremely Cold', icon: '🌨️', humidity: 90, wind: 30, visibility: 3, pressure: 1025 }, risk: 'high' },
'Auli': { weather: { temp: 12, condition: 'Cold', icon: '🏔️', humidity: 80, wind: 20, visibility: 6, pressure: 1020 }, risk: 'medium' },
'Gangotri': { weather: { temp: 6, condition: 'Very Cold', icon: '❄️', humidity: 88, wind: 28, visibility: 4, pressure: 1023 }, risk: 'high' },
'Yamunotri': { weather: { temp: 4, condition: 'Extremely Cold', icon: '🌨️', humidity: 92, wind: 32, visibility: 3, pressure: 1026 }, risk: 'high' },
'Almora': { weather: { temp: 22, condition: 'Pleasant', icon: '🌤️', humidity: 70, wind: 12, visibility: 10, pressure: 1016 }, risk: 'low' },
'Ranikhet': { weather: { temp: 19, condition: 'Cool', icon: '🏔️', humidity: 72, wind: 14, visibility: 9, pressure: 1017 }, risk: 'low' },
'Kausani': { weather: { temp: 17, condition: 'Cool', icon: '🏔️', humidity: 74, wind: 16, visibility: 8, pressure: 1018 }, risk: 'medium' },
'Lansdowne': { weather: { temp: 21, condition: 'Pleasant', icon: '🌤️', humidity: 68, wind: 10, visibility: 10, pressure: 1015 }, risk: 'low' },
'Chopta': { weather: { temp: 14, condition: 'Cool', icon: '🏔️', humidity: 78, wind: 18, visibility: 7, pressure: 1019 }, risk: 'medium' }
};
// Route network for pathfinding
const routeNetwork = {
'Dehradun': ['Rishikesh', 'Mussoorie', 'Haridwar', 'Chakrata', 'Dhanaulti'],
'Rishikesh': ['Dehradun', 'Devprayag', 'Srinagar (Garhwal)', 'Haridwar'],
'Devprayag': ['Rishikesh', 'Srinagar (Garhwal)', 'Tehri'],
'Srinagar (Garhwal)': ['Devprayag', 'Rudraprayag', 'Karnaprayag'],
'Rudraprayag': ['Srinagar (Garhwal)', 'Kedarnath', 'Guptkashi'],
'Karnaprayag': ['Srinagar (Garhwal)', 'Nandprayag', 'Joshimath'],
'Joshimath': ['Karnaprayag', 'Badrinath', 'Auli', 'Govindghat'],
'Badrinath': ['Joshimath', 'Mana'],
'Kedarnath': ['Rudraprayag', 'Guptkashi'],
'Gangotri': ['Uttarkashi', 'Barkot'],
'Yamunotri': ['Barkot', 'Purola'],
'Haridwar': ['Dehradun', 'Rishikesh', 'Roorkee'],
'Nainital': ['Haldwani', 'Bhimtal', 'Ranikhet'],
'Almora': ['Ranikhet', 'Kausani', 'Bageshwar'],
'Mussoorie': ['Dehradun', 'Dhanaulti']
};
// Map and routing state
let map;
let currentRoute = null;
let routeMarkers = [];
// Initialize map
function initMap() {
map = L.map('map').setView([30.0869, 78.2676], 8);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
}
// Create custom map markers
function createCustomIcon(color, letter) {
return L.divIcon({
html: `<div style="background-color: ${color}; width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 14px; border: 3px solid white; box-shadow: 0 3px 10px rgba(0,0,0,0.4);">${letter}</div>`,
className: 'custom-marker',
iconSize: [32, 32],
iconAnchor: [16, 16]
});
}
// Find route path using BFS
function findRoutePath(start, end) {
if (!start || !end) return [start, end];
if (routeNetwork && routeNetwork[start] && routeNetwork[start].includes(end)) return [start, end];
const queue = [[start]];
const visited = new Set([start]);
while (queue.length) {
const path = queue.shift();
const cur = path[path.length - 1];
if (cur === end) return path;
if (routeNetwork[cur]) {
for (const neigh of routeNetwork[cur]) {
if (!visited.has(neigh)) {
visited.add(neigh);
queue.push([...path, neigh]);
}
}
}
}
return [start, end];
}
// Weather fetch helpers
async function fetchWeatherByLatLon(lat, lon) {
try {
const url = `${OPENWEATHER_URL}?lat=${lat}&lon=${lon}&units=metric&appid=${OPENWEATHER_API_KEY}`;
const res = await fetch(url);
if (!res.ok) throw new Error('Weather fetch failed');
const data = await res.json();
return normalizeOpenWeather(data);
} catch (e) {
console.warn('Weather fetch error', e);
return null;
}
}
function normalizeOpenWeather(data) {
const w = data.weather && data.weather[0] ? data.weather[0] : { id: 800, main: 'Clear', description: '' };
const icon = weatherIdToEmoji(w.id);
return {
weather: {
temp: Math.round(data.main.temp),
condition: w.main || w.description || 'Clear',
icon: icon,
humidity: data.main.humidity,
wind: Math.round((data.wind && data.wind.speed) ? data.wind.speed * 3.6 : 0),
visibility: data.visibility ? Math.round(data.visibility / 1000) : 0,
pressure: data.main.pressure
},
risk: determineRisk(data)
};
}
function determineRisk(data) {
const windKmh = (data.wind && data.wind.speed) ? (data.wind.speed * 3.6) : 0;
const visKm = data.visibility ? (data.visibility / 1000) : 10;
const temp = data.main.temp;
if (windKmh > 40 || visKm < 2 || temp < -5 || temp > 45) return 'high';
if (windKmh > 25 || visKm < 5 || temp < 0 || temp > 35) return 'medium';
return 'low';
}
function weatherIdToEmoji(id) {
if (!id) return '🌤️';
if (id >= 200 && id < 300) return '⛈️';
if (id >= 300 && id < 600) return '🌧️';
if (id >= 600 && id < 700) return '❄️';
if (id >= 700 && id < 800) return '🌫️';
if (id === 800) return '☀️';
if (id === 801) return '🌤️';
if (id > 801 && id < 900) return '☁️';
return '🌤️';
}
// Add markers to map
function addMarkers(from, to) {
routeMarkers.forEach(m => map.removeLayer(m));
routeMarkers = [];
const fromCoords = locationCoords[from];
const toCoords = locationCoords[to];
const fromData = locationData[from] || { weather: { temp: 22, condition: 'Pleasant', icon: '🌤️' }, risk: 'low' };
const toData = locationData[to] || { weather: { temp: 18, condition: 'Pleasant', icon: '🌤️' }, risk: 'low' };
const startMarker = L.marker(fromCoords, { icon: createCustomIcon('#27ae60', 'S') }).addTo(map);
startMarker.bindPopup(`
<div class="custom-popup">
<div class="popup-title">${from} (Start)</div>
<div class="popup-weather">
<div class="popup-temp">${fromData.weather.temp}°C</div>
<div class="popup-condition">${fromData.weather.condition}</div>
</div>
</div>
`);
routeMarkers.push(startMarker);
const endMarker = L.marker(toCoords, { icon: createCustomIcon('#e74c3c', 'E') }).addTo(map);
endMarker.bindPopup(`
<div class="custom-popup">
<div class="popup-title">${to} (Destination)</div>
<div class="popup-weather">
<div class="popup-temp">${toData.weather.temp}°C</div>
<div class="popup-condition">${toData.weather.condition}</div>
</div>
</div>
`);
routeMarkers.push(endMarker);
const group = new L.featureGroup([startMarker, endMarker]);
map.fitBounds(group.getBounds().pad(0.1));
}
// Draw route using OSRM router
function drawRouteWithRouter(routePath, onStatsReady, onFail) {
const latlngs = routePath.map(city => locationCoords[city]);
const lngLatPairs = latlngs.map(([lat, lng]) => [lng, lat]);
const coordStr = lngLatPairs.map(([lng, lat]) => `${lng},${lat}`).join(";");
const url = `https://router.project-osrm.org/route/v1/driving/${coordStr}?overview=full&geometries=geojson&steps=false`;
fetch(url)
.then(res => res.json())
.then(data => {
if (!data || !data.routes || !data.routes.length) throw new Error("OSRM no route");
const route = data.routes[0];
const geometry = route.geometry;
renderGeoJSONRoute(geometry);
onStatsReady(route.distance, route.duration);
})
.catch(err => {
console.error(err);
onFail && onFail(err);
});
}
function renderGeoJSONRoute(geometry) {
if (currentRoute) map.removeLayer(currentRoute);
currentRoute = L.geoJSON(geometry, {
style: { color: '#667eea', weight: 5, opacity: 0.9 }
}).addTo(map);
try {
map.fitBounds(currentRoute.getBounds().pad(0.1));
} catch (e) {}
}
// Fallback curved route drawing
function createCurvedSegment(start, end) {
const points = [];
const numPoints = 15;
const latDiff = end[0] - start[0];
const lngDiff = end[1] - start[1];
const offsetLat = -lngDiff * 0.15 * (Math.random() * 0.5 + 0.75);
const offsetLng = latDiff * 0.15 * (Math.random() * 0.5 + 0.75);
const c1Lat = start[0] + latDiff * 0.33 + offsetLat * 0.5;
const c1Lng = start[1] + lngDiff * 0.33 + offsetLng * 0.5;
const c2Lat = start[0] + latDiff * 0.67 - offsetLat * 0.5;
const c2Lng = start[1] + lngDiff * 0.67 - offsetLng * 0.5;
for (let i = 0; i <= numPoints; i++) {
const t = i / numPoints;
const mt = 1 - t;
const lat = mt*mt*mt*start[0] + 3*mt*mt*t*c1Lat + 3*mt*t*t*c2Lat + t*t*t*end[0];
const lng = mt*mt*mt*start[1] + 3*mt*mt*t*c1Lng + 3*mt*t*t*c2Lng + t*t*t*end[1];
points.push([lat, lng]);
}
return points;
}
function drawFallbackCurvedRoute(routePath) {
if (currentRoute) map.removeLayer(currentRoute);
const routeCoords = routePath.map(city => locationCoords[city]);
const fullRoute = [];
for (let i = 0; i < routeCoords.length - 1; i++) {
const seg = createCurvedSegment(routeCoords[i], routeCoords[i + 1]);
if (i === routeCoords.length - 2) {
fullRoute.push(...seg);
} else {
fullRoute.push(...seg.slice(0, -1));
}
}
currentRoute = L.polyline(fullRoute, {
color: '#667eea',
weight: 5,
opacity: 0.9,
smoothFactor: 2,
dashArray: '10, 5'
}).addTo(map);
try {
map.fitBounds(currentRoute.getBounds().pad(0.1));
} catch (e) {}
}
// Loading states
function showLoading() {
document.getElementById('loading').classList.add('show');
document.getElementById('results').classList.remove('show');
}
function hideLoading() {
document.getElementById('loading').classList.remove('show');
document.getElementById('results').classList.add('show');
}
// Update display with route and weather information
function updateDisplay(route, destinationData, from, to) {
document.getElementById('distance').textContent = route.distance;
document.getElementById('duration').textContent = route.duration;
document.getElementById('routeType').textContent = route.type;
const weather = destinationData.weather;
document.getElementById('weatherLocation').textContent = to;
document.getElementById('weatherIcon').textContent = weather.icon;
document.getElementById('temperature').textContent = `${weather.temp}°C`;
document.getElementById('weatherCondition').textContent = weather.condition;
document.getElementById('humidity').textContent = `${weather.humidity}%`;
document.getElementById('windSpeed').textContent = `${weather.wind} km/h`;
document.getElementById('visibility').textContent = `${weather.visibility} km`;
document.getElementById('pressure').textContent = `${weather.pressure} hPa`;
const alertElement = document.getElementById('alertStatus');
const risk = destinationData.risk;
alertElement.className = 'alert-status';
if (risk === 'low') {
alertElement.classList.add('alert-green');
alertElement.textContent = '✓ Good conditions - Safe to travel';
} else if (risk === 'medium') {
alertElement.classList.add('alert-yellow');
alertElement.textContent = '⚠ Moderate conditions - Exercise caution';
} else {
alertElement.classList.add('alert-red');
alertElement.textContent = '⚠ High alert - Extreme weather conditions, travel with caution';
}
if (route.path && route.path.length > 2) {
const pathText = `Via: ${route.path.slice(1, -1).join(' → ')}`;
alertElement.textContent += `\n${pathText}`;
alertElement.style.whiteSpace = 'pre-line';
}
}
// Autocomplete functionality
function setupAutocomplete() {
const fromInput = document.getElementById('fromLocation');
const toInput = document.getElementById('toLocation');
const fromSuggestions = document.getElementById('fromSuggestions');
const toSuggestions = document.getElementById('toSuggestions');
function showSuggestions(input, suggestions, value) {
const filtered = allLocations
.filter(location => location.toLowerCase().includes(value.toLowerCase()))
.sort((a,b) => a.localeCompare(b))
.slice(0, 8);
if (filtered.length > 0 && value.length > 0) {
suggestions.innerHTML = filtered
.map(location => `<div class="suggestion-item" onclick="selectLocation('${input.id}','${location}')">${location}</div>`)
.join('');
suggestions.style.display = 'block';
} else {
suggestions.style.display = 'none';
}
}
fromInput.addEventListener('input', (e) => showSuggestions(fromInput, fromSuggestions, e.target.value));
toInput.addEventListener('input', (e) => showSuggestions(toInput, toSuggestions, e.target.value));
document.addEventListener('click', (e) => {
if (!e.target.closest('.input-group')) {
fromSuggestions.style.display = 'none';
toSuggestions.style.display = 'none';
}
});
}
function selectLocation(inputId, location) {
document.getElementById(inputId).value = location;
document.getElementById(inputId.replace('Location', 'Suggestions')).style.display = 'none';
}
// Plan route function
async function planRoute() {
const from = document.getElementById('fromLocation').value.trim();
const to = document.getElementById('toLocation').value.trim();
if (!from || !to) {
alert('Please enter both starting point and destination');
return;
}
if (from.toLowerCase() === to.toLowerCase()) {
alert('Starting point and destination cannot be the same');
return;
}
if (!locationCoords[from] || !locationCoords[to]) {
alert('Location not found. Please check spelling or try alternative names.');
return;
}
showLoading();
const routePath = findRoutePath(from, to);
const hasHighAltitude = routePath.some(city =>
['Badrinath', 'Kedarnath', 'Gangotri', 'Yamunotri', 'Hemkund Sahib'].includes(city)
);
const routeType = hasHighAltitude ? 'High Altitude' : routePath.length > 2 ? 'Mountain' : 'Regional';
addMarkers(from, to);
drawRouteWithRouter(routePath,
async (distanceMeters, durationSeconds) => {
const km = Math.round(distanceMeters / 100) / 10;
const hours = Math.floor(durationSeconds / 3600);
const minutes = Math.round((durationSeconds % 3600) / 60);
const route = {
distance: `${km} km`,
duration: `${hours}h ${minutes}m`,
type: routeType,
path: routePath
};
const [lat, lon] = locationCoords[to];
const live = await fetchWeatherByLatLon(lat, lon);
const destinationData = live || (locationData[to] || {
weather: { temp: 20, condition: 'Pleasant', icon: '🌤️', humidity: 70, wind: 12, visibility: 10, pressure: 1015 },
risk: 'low'
});
updateDisplay(route, destinationData, from, to);
hideLoading();
},
async (err) => {
console.warn('Routing failed, using fallback curve:', err);
drawFallbackCurvedRoute(routePath);
let totalDistance = 0;
for (let i = 0; i < routePath.length - 1; i++) {
const c1 = locationCoords[routePath[i]];
const c2 = locationCoords[routePath[i + 1]];
totalDistance += calculateDistance(c1, c2);
}
let avgSpeed = hasHighAltitude ? 25 : totalDistance > 400 ? 45 : totalDistance > 150 ? 35 : 40;
const totalHours = totalDistance / avgSpeed;
const h = Math.floor(totalHours);
const m = Math.round((totalHours - h) * 60);
const route = {
distance: `${Math.round(totalDistance)} km`,
duration: `${h}h ${m}m`,
type: routeType,
path: routePath
};
const [lat, lon] = locationCoords[to];
const live = await fetchWeatherByLatLon(lat, lon);
const destinationData = live || (locationData[to] || {
weather: { temp: 20, condition: 'Pleasant', icon: '🌤️', humidity: 70, wind: 12, visibility: 10, pressure: 1015 },
risk: 'low'
});
updateDisplay(route, destinationData, from, to);
hideLoading();
}
);
}
// Calculate distance using haversine formula
function calculateDistance(coord1, coord2) {
const R = 6371;
const dLat = (coord2[0] - coord1[0]) * Math.PI / 180;
const dLon = (coord2[1] - coord1[1]) * Math.PI / 180;
const a = Math.sin(dLat/2) ** 2 +
Math.cos(coord1[0] * Math.PI / 180) * Math.cos(coord2[0] * Math.PI / 180) *
Math.sin(dLon/2) ** 2;
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
// Page Navigation
function showHome() {
document.getElementById('home-page').style.display = 'block';
document.getElementById('maps-page').classList.remove('active');
document.getElementById('chatbot-page').classList.remove('active');
}
function showMaps() {
document.getElementById('home-page').style.display = 'none';
document.getElementById('maps-page').classList.add('active');
// Initialize map when maps section is shown
if (!map) {
setTimeout(() => {
initMap();
}, 100);
}
}
function showChatbot() {
document.getElementById('home-page').style.display = 'none';
document.getElementById('chatbot-page').classList.add('active');
}
// Slider functionality
let currentSlide = 0;
let autoSlideInterval;
let isHovered = false;
const slides = [
"Emergency Preparedness Made Easy<br>Your comprehensive disaster management companion",
"Real-time Weather Updates<br>Stay informed with accurate weather forecasts and alerts",
"Interactive Route Planning<br>Find safe routes and avoid danger zones during emergencies",
"24/7 AI Assistant<br>Get instant help and guidance for any emergency situation"
];
const dots = document.querySelectorAll('.dot');
const sliderText = document.getElementById('sliderText');
const sliderContainer = document.querySelector('.slider-container');
function showSlide(index) {
dots.forEach(dot => dot.classList.remove('active'));
dots[index].classList.add('active');
sliderText.innerHTML = slides[index];
currentSlide = index;
}
function nextSlide() {
currentSlide = (currentSlide + 1) % slides.length;
showSlide(currentSlide);
}
function startAutoSlide() {
autoSlideInterval = setInterval(nextSlide, 3000);
}
function stopAutoSlide() {
clearInterval(autoSlideInterval);
}
startAutoSlide();
if (sliderContainer) {
sliderContainer.addEventListener('mouseenter', () => {
isHovered = true;
stopAutoSlide();
});
sliderContainer.addEventListener('mouseleave', () => {
isHovered = false;
startAutoSlide();
});
}
dots.forEach((dot, index) => {
dot.addEventListener('click', () => {
showSlide(index);
if (!isHovered) {
stopAutoSlide();
startAutoSlide();
}
});
});
// Chatbot functionality
let userMessage = null;
const API_KEY = " ";
const API_URL = `https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key=${API_KEY}`;
const createChatLi = (message, className) => {
const chatLi = document.createElement("li");
chatLi.classList.add("chat", className);
if (className === "outgoing") {
chatLi.innerHTML = `<p>${message}</p><div class="avatar"></div>`;
} else {
chatLi.innerHTML = `
<div class="avatar">
<span class="material-symbols-outlined">smart_toy</span>
</div>
<p>${message}</p>
`;
}
return chatLi;
};
const showTypingIndicator = () => {
const typingLi = document.createElement("li");
typingLi.classList.add("chat", "incoming");
typingLi.innerHTML = `
<div class="avatar">
<span class="material-symbols-outlined">smart_toy</span>
</div>
<div class="typing-indicator">
<div class="typing-dot"></div>
<div class="typing-dot"></div>
<div class="typing-dot"></div>
</div>
`;
return typingLi;
};
const generateResponse = async (chatElement) => {
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contents: [{
role: "user",
parts: [{ text: userMessage }]
}]
}),
};
try {
const response = await fetch(API_URL, requestOptions);
const data = await response.json();
if (!response.ok) throw new Error(data.error.message);
chatElement.innerHTML = `
<div class="avatar">
<span class="material-symbols-outlined">smart_toy</span>
</div>
<p>${data.candidates[0].content.parts[0].text.replace(/\*\*(.*?)\*\*/g, '$1')}</p>
`;
} catch (error) {
chatElement.innerHTML = `
<div class="avatar">
<span class="material-symbols-outlined">smart_toy</span>
</div>
<p class="error">${error.message}</p>
`;
console.error('API Error:', error);
} finally {
const chatbox = document.querySelector(".chatbox");
if (chatbox) chatbox.scrollTo(0, chatbox.scrollHeight);
}
};
const handleChat = () => {
const chatInput = document.querySelector(".chat-input");
const chatbox = document.querySelector(".chatbox");
if (!chatInput || !chatbox) return;
userMessage = chatInput.value.trim();
if (!userMessage) return;
chatInput.value = "";
chatInput.style.height = "auto";
chatbox.appendChild(createChatLi(userMessage, "outgoing"));
chatbox.scrollTo(0, chatbox.scrollHeight);
setTimeout(() => {
const typingIndicator = showTypingIndicator();
chatbox.appendChild(typingIndicator);
chatbox.scrollTo(0, chatbox.scrollHeight);
generateResponse(typingIndicator);
}, 600);
};
// Initialize everything when DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
// Initialize autocomplete for maps section
setupAutocomplete();
// Initialize chatbot
const chatInput = document.querySelector(".chat-input");
const sendBtn = document.querySelector(".send-btn");
if (chatInput) {
chatInput.addEventListener("input", () => {
chatInput.style.height = "auto";
chatInput.style.height = chatInput.scrollHeight + "px";
});
chatInput.addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleChat();
}
});
}
if (sendBtn) {
sendBtn.addEventListener("click", handleChat);
}
});
// Expose functions to global scope
window.selectLocation = selectLocation;
window.planRoute = planRoute;
window.showHome = showHome;
window.showMaps = showMaps;
window.showChatbot = showChatbot;