-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1686 lines (1456 loc) · 61.3 KB
/
script.js
File metadata and controls
1686 lines (1456 loc) · 61.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
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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ===== GLOBAL VARIABLES =====
let currentCity = null; // Will be set when user searches
let weatherData = null;
let airQualityData = null;
let map = null; // Google Maps instance
let marker = null; // Map marker
let autocomplete = null; // Google Places Autocomplete
let googleMapsReady = false; // Flag to track if Google Maps is loaded
let tempChart = null; // Chart.js instance for temperature
let aqiChart = null; // Chart.js instance for air quality
let weatherChart = null; // Chart.js instance for weather metrics
// ===== API CONFIGURATION =====
// API keys are loaded from config.js file (not committed to git)
// If config.js doesn't exist, show error
if (typeof API_CONFIG === 'undefined') {
console.error('❌ ERROR: config.js file not found!');
console.error('Please create config.js with your API keys.');
alert('Configuration file missing! Please create config.js with your API keys.');
// Fallback empty config to prevent errors
window.API_CONFIG = {
openWeather: {
key: '',
baseUrl: 'https://api.openweathermap.org/data/2.5',
endpoints: { weather: '/weather', airPollution: '/air_pollution' }
},
googleMaps: {
key: '',
libraries: ['places'],
baseUrl: 'https://maps.googleapis.com/maps/api'
}
};
// Also set API_KEYS for backward compatibility
window.API_KEYS = {
openWeather: '',
googleMaps: ''
};
}
// ===== GOOGLE MAPS CALLBACK =====
// This is called when Google Maps API finishes loading
function initGoogleMaps() {
googleMapsReady = true;
console.log("✅ Google Maps API loaded successfully");
// Initialize map
initializeGoogleMap();
// Initialize autocomplete for search
initializeAutocomplete();
}
// ===== INITIALIZATION =====
// This function runs when the page loads
function init() {
updateCurrentTime();
setInterval(updateCurrentTime, 1000); // Update time every second
// Load Google Maps API dynamically
loadGoogleMapsAPI();
// Show welcome message
console.log("Smart City Dashboard Loaded!");
console.log("APIs: OpenWeatherMap + Google Maps");
console.log("Search for a city to see real-time data!");
}
// ===== LOAD GOOGLE MAPS API DYNAMICALLY =====
function loadGoogleMapsAPI() {
const script = document.getElementById('google-maps-script');
if (script) {
const libraries = API_CONFIG.googleMaps.libraries.join(',');
const callback = 'initGoogleMaps';
script.src = `https://maps.googleapis.com/maps/api/js?key=${API_CONFIG.googleMaps.key}&libraries=${libraries}&callback=${callback}`;
}
}
// ===== UPDATE CURRENT TIME =====
function updateCurrentTime() {
const now = new Date();
const timeString = now.toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
const dateString = now.toLocaleDateString('en-US', {
weekday: 'long',
month: 'long',
day: 'numeric'
});
document.getElementById('currentTime').textContent = `${dateString} - ${timeString}`;
}
// ===== NAVIGATION BETWEEN SECTIONS =====
function showSection(sectionName) {
// Hide all sections
const sections = document.querySelectorAll('.content-section');
sections.forEach(section => {
section.classList.remove('active');
});
// Show selected section
const targetSection = document.getElementById(sectionName);
if (targetSection) {
targetSection.classList.add('active');
}
// Update active menu item
const menuItems = document.querySelectorAll('.menu-item');
menuItems.forEach(item => {
item.classList.remove('active');
});
event.currentTarget.classList.add('active');
console.log(`Switched to ${sectionName} section`);
}
// ===== SEARCH CITY =====
function searchCity() {
const searchInput = document.getElementById('citySearch');
let cityName = searchInput.value.trim();
if (cityName === "") {
alert("Please enter a city name!");
return;
}
// If using Google Places autocomplete, extract just the city name
// Remove country and other details if present
const cityParts = cityName.split(',');
cityName = cityParts[0].trim(); // Take first part (city name)
currentCity = cityName;
document.getElementById('selectedCity').textContent = cityName;
console.log(`🔍 Fetching data for city: ${cityName}`);
// PRIMARY: Get coordinates from Google Geocoding FIRST (most accurate)
if (googleMapsReady) {
geocodeCityForData(cityName);
} else {
// Fallback: Use OpenWeather to get coordinates
fetchWeatherData(cityName);
}
}
// ===== FETCH WEATHER DATA FROM OPENWEATHERMAP =====
async function fetchWeatherData(city) {
try {
// Show loading state
document.getElementById('temperature').textContent = "...";
document.getElementById('weatherDesc').textContent = "Loading...";
// Build API URL from config
const baseUrl = API_CONFIG.openWeather.baseUrl;
const endpoint = API_CONFIG.openWeather.endpoints.weather;
const url = `${baseUrl}${endpoint}?q=${encodeURIComponent(city)}&appid=${API_CONFIG.openWeather.key}&units=metric`;
console.log(`🌤️ Fetching weather for: ${city}`);
const startTime = performance.now();
// Fetch data from API
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
const endTime = performance.now();
const duration = (endTime - startTime).toFixed(0);
if (data.cod === 200) {
weatherData = data;
updateWeatherDisplay(data);
updateRawDataTables(data, 'weather');
console.log(`✅ Weather data fetched successfully in ${duration}ms`, data);
// Trigger air quality fetch after weather data is loaded (has coordinates)
fetchAirQualityData(city, data.coord);
// Update charts with real API data
updateCharts();
return data;
} else {
console.error("❌ Weather API Error:", data.message);
alert(`Error: ${data.message}. Try another city name.`);
document.getElementById('weatherDesc').textContent = "City not found";
return null;
}
} catch (error) {
console.error("❌ Error fetching weather data:", error);
alert("Failed to fetch weather data. Check your internet connection.");
document.getElementById('weatherDesc').textContent = "Failed to load";
return null;
}
}
// ===== FETCH AIR QUALITY DATA FROM GOOGLE AIR QUALITY API =====
async function fetchAirQualityData(city, coordinates = null) {
try {
// Get coordinates from parameter or existing weather data
let lat, lon;
if (coordinates) {
lat = coordinates.lat;
lon = coordinates.lon;
} else if (weatherData && weatherData.coord) {
lat = weatherData.coord.lat;
lon = weatherData.coord.lon;
} else {
console.log("⏳ Waiting for weather data to get coordinates...");
// If weather data not available yet, fetch it first
const weatherInfo = await fetchWeatherData(city);
if (!weatherInfo || !weatherInfo.coord) {
console.error("❌ Cannot get coordinates for air quality");
return;
}
lat = weatherInfo.coord.lat;
lon = weatherInfo.coord.lon;
}
// Show loading state
document.getElementById('aqiValue').textContent = "...";
document.getElementById('aqiStatus').textContent = "Loading...";
// Build Google Air Quality API URL
const baseUrl = API_CONFIG.googleAirQuality.baseUrl;
const url = `${baseUrl}/currentConditions:lookup?key=${API_CONFIG.googleAirQuality.key}`;
console.log(`🌬️ Fetching Google Air Quality for coordinates: ${lat}, ${lon}`);
const startTime = performance.now();
// Prepare request payload for Google API
const payload = {
location: {
latitude: lat,
longitude: lon
}
};
// Fetch data from Google Air Quality API
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
if (!response.ok) {
console.warn(`⚠️ Google Air Quality API error: ${response.status}, falling back to OpenWeather`);
// Fallback to OpenWeatherMap
return fetchAirQualityDataOpenWeather(lat, lon, city);
}
const data = await response.json();
const endTime = performance.now();
const duration = (endTime - startTime).toFixed(0);
if (data && data.indexes) {
airQualityData = data;
updateAirQualityDisplayGoogle(data);
updateRawDataTables(data, 'aqi_google');
console.log(`✅ Google Air Quality data fetched successfully in ${duration}ms`, data);
// Update JSON display with all available data
updateJSONDisplay();
// Update charts with air quality data
updateCharts();
} else {
console.warn("⚠️ No Google AQI data, trying OpenWeather fallback");
return fetchAirQualityDataOpenWeather(lat, lon, city);
}
} catch (error) {
console.error("❌ Error fetching Google Air Quality data:", error);
console.log("🔄 Falling back to OpenWeather Air Quality");
// Fallback to OpenWeatherMap
return fetchAirQualityDataOpenWeather(lat, lon, city);
}
}
// ===== FALLBACK: FETCH AIR QUALITY FROM OPENWEATHERMAP =====
async function fetchAirQualityDataOpenWeather(lat, lon, city) {
try {
const baseUrl = API_CONFIG.openWeather.baseUrl;
const endpoint = API_CONFIG.openWeather.endpoints.airPollution;
const url = `${baseUrl}${endpoint}?lat=${lat}&lon=${lon}&appid=${API_CONFIG.openWeather.key}`;
console.log(`🌬️ Fetching OpenWeather Air Quality (fallback) for: ${city}`);
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (data.list && data.list.length > 0) {
airQualityData = data.list[0];
updateAirQualityDisplay(airQualityData);
updateRawDataTables(airQualityData, 'aqi');
console.log(`✅ OpenWeather Air Quality data fetched (fallback)`, airQualityData);
updateJSONDisplay();
// Update charts with air quality data
updateCharts();
} else {
document.getElementById('aqiStatus').textContent = "Data not available";
}
} catch (error) {
console.error("❌ Error fetching OpenWeather Air Quality:", error);
document.getElementById('aqiStatus').textContent = "Failed to load";
}
}
// ===== UPDATE WEATHER DISPLAY =====
function updateWeatherDisplay(data) {
// Temperature
document.getElementById('temperature').textContent = Math.round(data.main.temp);
document.getElementById('feelsLike').textContent = Math.round(data.main.feels_like);
// Weather description
document.getElementById('weatherDesc').textContent = data.weather[0].description.toUpperCase();
// Other weather info
document.getElementById('windSpeed').textContent = `${data.wind.speed} km/h`;
document.getElementById('humidity').textContent = `${data.main.humidity}%`;
document.getElementById('visibility').textContent = `${(data.visibility / 1000).toFixed(1)} km`;
document.getElementById('pressure').textContent = `${data.main.pressure} hPa`;
// Sunrise and Sunset
const sunrise = new Date(data.sys.sunrise * 1000).toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit'
});
const sunset = new Date(data.sys.sunset * 1000).toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit'
});
document.getElementById('sunrise').textContent = sunrise;
document.getElementById('sunset').textContent = sunset;
// Last update time
const lastUpdate = new Date().toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit'
});
document.getElementById('lastUpdate').textContent = lastUpdate;
// Map location data
document.getElementById('mapCity').textContent = data.name;
document.getElementById('coordinates').textContent = `${data.coord.lat.toFixed(2)}, ${data.coord.lon.toFixed(2)}`;
document.getElementById('timezone').textContent = `UTC ${data.timezone / 3600 > 0 ? '+' : ''}${(data.timezone / 3600).toFixed(1)}`;
// Update Google Map with city location
updateGoogleMap(data.coord.lat, data.coord.lon, data.name);
// Fetch city details from Google Places API
fetchCityDetails(data.name, data.coord.lat, data.coord.lon);
// Generate AI city description
generateCityDescription(data.name, data);
}
// ===== UPDATE AIR QUALITY DISPLAY (GOOGLE API) =====
function updateAirQualityDisplayGoogle(data) {
// Google Air Quality API returns indexes array
// Find the US AQI or universal AQI
let aqiIndex = data.indexes.find(idx => idx.code === 'uaqi') || data.indexes[0];
if (!aqiIndex) {
console.error("No AQI index found in Google data");
return;
}
const aqiValue = aqiIndex.aqi;
const dominantPollutant = aqiIndex.dominantPollutant || "N/A";
// Log full data to see what Google is sending
console.log(`📊 Full Google AQI Data:`, aqiIndex);
// Determine status and color based on AQI value (IGNORE Google's category - use our own logic)
let aqiStatus, aqiClass, healthMessage;
if (aqiValue <= 50) {
aqiStatus = "Good";
healthMessage = "Air quality is excellent";
aqiClass = "aqi-good";
} else if (aqiValue <= 100) {
aqiStatus = "Moderate";
healthMessage = "Air quality is acceptable";
aqiClass = "aqi-moderate";
} else if (aqiValue <= 150) {
aqiStatus = "Unhealthy for Sensitive";
healthMessage = "May affect sensitive people";
aqiClass = "aqi-moderate";
} else if (aqiValue <= 200) {
aqiStatus = "Unhealthy";
healthMessage = "Everyone may experience health effects";
aqiClass = "aqi-unhealthy";
} else if (aqiValue <= 300) {
aqiStatus = "Very Unhealthy";
healthMessage = "Health alert - everyone may be affected";
aqiClass = "aqi-unhealthy";
} else {
aqiStatus = "Hazardous";
healthMessage = "Health warning of emergency conditions";
aqiClass = "aqi-unhealthy";
}
const aqiValueElement = document.getElementById('aqiValue');
const aqiStatusElement = document.getElementById('aqiStatus');
// Update AQI value
aqiValueElement.textContent = aqiValue;
// Remove all AQI classes
aqiValueElement.classList.remove('aqi-good', 'aqi-moderate', 'aqi-unhealthy');
// Add appropriate class
aqiValueElement.classList.add(aqiClass);
// Set proper status text
aqiStatusElement.textContent = `${aqiStatus} - ${healthMessage}`;
console.log(`📊 Google AQI: ${aqiValue} | Status: ${aqiStatus} | Dominant: ${dominantPollutant}`);
}
// ===== UPDATE AIR QUALITY DISPLAY (OPENWEATHER - FALLBACK) =====
function updateAirQualityDisplay(data) {
// OpenWeatherMap returns AQI in data.main.aqi (1-5 scale)
// 1 = Good, 2 = Fair, 3 = Moderate, 4 = Poor, 5 = Very Poor
const aqi = data.main.aqi;
// Convert to US AQI scale (0-500) for display
// This is an approximation
let aqiValue, aqiStatus, aqiClass;
switch(aqi) {
case 1:
aqiValue = 25;
aqiStatus = "Good - Air quality is excellent (OpenWeather)";
aqiClass = "aqi-good";
break;
case 2:
aqiValue = 60;
aqiStatus = "Fair - Air quality is acceptable (OpenWeather)";
aqiClass = "aqi-good";
break;
case 3:
aqiValue = 100;
aqiStatus = "Moderate - May affect sensitive people (OpenWeather)";
aqiClass = "aqi-moderate";
break;
case 4:
aqiValue = 150;
aqiStatus = "Poor - Health effects for everyone (OpenWeather)";
aqiClass = "aqi-unhealthy";
break;
case 5:
aqiValue = 250;
aqiStatus = "Very Poor - Serious health effects (OpenWeather)";
aqiClass = "aqi-unhealthy";
break;
default:
aqiValue = "--";
aqiStatus = "Unknown";
aqiClass = "aqi-good";
}
const aqiValueElement = document.getElementById('aqiValue');
const aqiStatusElement = document.getElementById('aqiStatus');
// Update AQI value
aqiValueElement.textContent = aqiValue;
// Remove all AQI classes
aqiValueElement.classList.remove('aqi-good', 'aqi-moderate', 'aqi-unhealthy');
// Add appropriate class
aqiValueElement.classList.add(aqiClass);
aqiStatusElement.textContent = aqiStatus;
}
// ===== UPDATE RAW DATA TABLES =====
function updateRawDataTables(data, type) {
if (type === 'weather') {
const tableBody = document.getElementById('weatherDataTable');
tableBody.innerHTML = `
<tr>
<td>Temperature</td>
<td>${Math.round(data.main.temp)}</td>
<td>°C</td>
</tr>
<tr>
<td>Feels Like</td>
<td>${Math.round(data.main.feels_like)}</td>
<td>°C</td>
</tr>
<tr>
<td>Min Temperature</td>
<td>${Math.round(data.main.temp_min)}</td>
<td>°C</td>
</tr>
<tr>
<td>Max Temperature</td>
<td>${Math.round(data.main.temp_max)}</td>
<td>°C</td>
</tr>
<tr>
<td>Humidity</td>
<td>${data.main.humidity}</td>
<td>%</td>
</tr>
<tr>
<td>Pressure</td>
<td>${data.main.pressure}</td>
<td>hPa</td>
</tr>
<tr>
<td>Wind Speed</td>
<td>${data.wind.speed}</td>
<td>m/s</td>
</tr>
<tr>
<td>Wind Direction</td>
<td>${data.wind.deg || 'N/A'}</td>
<td>degrees</td>
</tr>
<tr>
<td>Visibility</td>
<td>${(data.visibility / 1000).toFixed(1)}</td>
<td>km</td>
</tr>
<tr>
<td>Cloudiness</td>
<td>${data.clouds.all}</td>
<td>%</td>
</tr>
`;
}
if (type === 'aqi_google') {
const tableBody = document.getElementById('aqiDataTable');
let tableHTML = '';
// Google Air Quality data structure
if (data.indexes && data.indexes.length > 0) {
data.indexes.forEach(index => {
tableHTML += `
<tr>
<td>${index.displayName || index.code}</td>
<td>AQI: ${index.aqi}</td>
<td>${index.category || 'N/A'}</td>
</tr>
`;
});
}
// Add pollutant data if available
if (data.pollutants && data.pollutants.length > 0) {
data.pollutants.forEach(pollutant => {
const concentration = pollutant.concentration?.value || 'N/A';
const unit = pollutant.concentration?.units || '';
tableHTML += `
<tr>
<td>${pollutant.displayName || pollutant.code}</td>
<td>${concentration} ${unit}</td>
<td>Google Data</td>
</tr>
`;
});
}
tableBody.innerHTML = tableHTML || '<tr><td colspan="3" class="no-data">No air quality data available</td></tr>';
}
if (type === 'aqi') {
const tableBody = document.getElementById('aqiDataTable');
const components = data.components;
let tableHTML = '';
// Define pollutant names and their units
const pollutants = {
'co': { name: 'Carbon Monoxide (CO)', unit: 'μg/m³' },
'no': { name: 'Nitrogen Monoxide (NO)', unit: 'μg/m³' },
'no2': { name: 'Nitrogen Dioxide (NO2)', unit: 'μg/m³' },
'o3': { name: 'Ozone (O3)', unit: 'μg/m³' },
'so2': { name: 'Sulphur Dioxide (SO2)', unit: 'μg/m³' },
'pm2_5': { name: 'PM2.5', unit: 'μg/m³' },
'pm10': { name: 'PM10', unit: 'μg/m³' },
'nh3': { name: 'Ammonia (NH3)', unit: 'μg/m³' }
};
for (let pollutant in components) {
const value = components[pollutant];
const pollutantInfo = pollutants[pollutant] || { name: pollutant.toUpperCase(), unit: 'μg/m³' };
// Determine status based on value (simplified)
let status = 'Good';
if (value > 50) status = 'Moderate';
if (value > 100) status = 'Unhealthy';
tableHTML += `
<tr>
<td>${pollutantInfo.name}</td>
<td>${value.toFixed(2)} ${pollutantInfo.unit}</td>
<td>${status} (Fallback)</td>
</tr>
`;
}
tableBody.innerHTML = tableHTML || '<tr><td colspan="3" class="no-data">No air quality data available</td></tr>';
}
}
// ===== GOOGLE MAPS INTEGRATION =====
// Initialize Google Map (empty map on load)
function initializeGoogleMap() {
// Check if Google Maps API is loaded
if (typeof google === 'undefined' || !google.maps) {
console.error("Google Maps API not loaded");
return;
}
const mapContainer = document.getElementById('mapContainer');
if (!mapContainer) {
console.error("Map container not found");
return;
}
// Default center (world view)
const defaultCenter = { lat: 20.0, lng: 0.0 };
try {
// Initialize map
map = new google.maps.Map(mapContainer, {
center: defaultCenter,
zoom: 2,
mapTypeControl: true,
streetViewControl: true,
fullscreenControl: true,
zoomControl: true
});
console.log("✅ Google Map initialized successfully");
} catch (error) {
console.error("Error initializing Google Map:", error);
}
}
// Update map with city location
function updateGoogleMap(lat, lon, cityName) {
// Check if Google Maps API is loaded
if (typeof google === 'undefined' || !google.maps) {
console.error("Google Maps API not loaded");
return;
}
// If map not initialized, initialize it now
if (!map) {
initializeGoogleMap();
}
if (!map) {
console.error("Map not initialized");
return;
}
const location = { lat: lat, lng: lon };
try {
// Center map on city
map.setCenter(location);
map.setZoom(12);
// Remove existing marker if any
if (marker) {
marker.setMap(null);
}
// Add new marker
marker = new google.maps.Marker({
position: location,
map: map,
title: cityName,
animation: google.maps.Animation.DROP
});
// Add info window
const infoWindow = new google.maps.InfoWindow({
content: `
<div style="padding: 10px;">
<h3 style="margin: 0 0 5px 0; color: #667eea;">${cityName}</h3>
<p style="margin: 0; color: #666;">Lat: ${lat.toFixed(4)}, Lng: ${lon.toFixed(4)}</p>
</div>
`
});
marker.addListener('click', () => {
infoWindow.open(map, marker);
});
console.log(`✅ Map updated for ${cityName} at ${lat}, ${lon}`);
} catch (error) {
console.error("Error updating map:", error);
}
}
// Initialize Google Places Autocomplete for search input
function initializeAutocomplete() {
if (typeof google === 'undefined' || !google.maps || !google.maps.places) {
console.warn("Google Places API not available - search will work without autocomplete");
return;
}
const searchInput = document.getElementById('citySearch');
if (!searchInput) {
console.error("Search input not found");
return;
}
try {
// Create autocomplete object with options that don't interfere with typing
autocomplete = new google.maps.places.Autocomplete(searchInput, {
types: ['(cities)'], // Restrict to cities only
fields: ['name', 'geometry', 'formatted_address']
});
// Allow normal typing by not preventing default behavior
searchInput.setAttribute('autocomplete', 'off');
// When user selects a place from autocomplete
autocomplete.addListener('place_changed', () => {
const place = autocomplete.getPlace();
if (!place.geometry) {
console.warn("No geometry found for place");
return;
}
// Extract city name
const cityName = place.name || place.formatted_address.split(',')[0];
// Update search input
searchInput.value = cityName;
// Get coordinates
const lat = place.geometry.location.lat();
const lng = place.geometry.location.lng();
console.log(`📍 Place selected: ${cityName} at ${lat}, ${lng}`);
// Update map immediately with Google coordinates
updateGoogleMap(lat, lng, cityName);
// Fetch weather data (which will trigger air quality and energy automatically)
currentCity = cityName;
document.getElementById('selectedCity').textContent = cityName;
fetchWeatherData(cityName);
});
console.log("✅ Google Places Autocomplete initialized");
} catch (error) {
console.error("Error initializing autocomplete:", error);
}
}
// ===== PRIMARY: GEOCODE CITY USING GOOGLE (GET ACCURATE COORDINATES FIRST) =====
async function geocodeCityForData(cityName) {
if (!googleMapsReady) {
console.warn("Google Maps not ready, falling back to OpenWeather");
fetchWeatherData(cityName);
return;
}
try {
console.log(`📍 [PRIMARY] Getting coordinates from Google Geocoding for: ${cityName}`);
const geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: cityName }, async (results, status) => {
if (status === 'OK' && results[0]) {
const location = results[0].geometry.location;
const lat = location.lat();
const lng = location.lng();
console.log(`✅ [PRIMARY] Google coordinates for ${cityName}: ${lat}, ${lng}`);
// Update map immediately with Google coordinates
updateGoogleMap(lat, lng, cityName);
// Update location details
document.getElementById('coordinates').textContent = `${lat.toFixed(2)}, ${lng.toFixed(2)}`;
// Fetch city details from Google
fetchCityDetails(cityName, lat, lng);
// NOW use Google coordinates for all APIs (more accurate!)
// Fetch weather using coordinates (more accurate than city name)
await fetchWeatherDataByCoordinates(lat, lng, cityName);
// Fetch air quality using Google coordinates
await fetchAirQualityData(cityName, { lat, lon: lng });
} else {
console.warn(`⚠️ Google Geocoding failed for ${cityName}: ${status}, using OpenWeather fallback`);
// Fallback to OpenWeather
fetchWeatherData(cityName);
}
});
} catch (error) {
console.error("❌ Error in Google geocoding:", error);
// Fallback to OpenWeather
fetchWeatherData(cityName);
}
}
// ===== FETCH WEATHER BY COORDINATES (MORE ACCURATE) =====
async function fetchWeatherDataByCoordinates(lat, lon, cityName) {
try {
// Show loading state
document.getElementById('temperature').textContent = "...";
document.getElementById('weatherDesc').textContent = "Loading...";
// Use coordinates instead of city name (more accurate!)
const baseUrl = API_CONFIG.openWeather.baseUrl;
const endpoint = API_CONFIG.openWeather.endpoints.weather;
const url = `${baseUrl}${endpoint}?lat=${lat}&lon=${lon}&appid=${API_CONFIG.openWeather.key}&units=metric`;
console.log(`🌤️ [PRIMARY] Fetching weather using Google coordinates: ${lat}, ${lon}`);
const startTime = performance.now();
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
const endTime = performance.now();
const duration = (endTime - startTime).toFixed(0);
if (data.cod === 200) {
weatherData = data;
updateWeatherDisplay(data);
updateRawDataTables(data, 'weather');
console.log(`✅ Weather data fetched using Google coordinates in ${duration}ms`);
// Update charts with real API data
updateCharts();
return data;
} else {
console.error("❌ Weather API Error:", data.message);
document.getElementById('weatherDesc').textContent = "City not found";
return null;
}
} catch (error) {
console.error("❌ Error fetching weather data:", error);
document.getElementById('weatherDesc').textContent = "Failed to load";
return null;
}
}
// Geocode city name to get coordinates (backup method)
async function geocodeCity(cityName) {
if (!googleMapsReady) {
return;
}
try {
const geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: cityName }, (results, status) => {
if (status === 'OK' && results[0]) {
const location = results[0].geometry.location;
const lat = location.lat();
const lng = location.lng();
console.log(`✅ Geocoded ${cityName}: ${lat}, ${lng}`);
// Update map if not already updated
if (map && (!marker || marker.getPosition().lat() !== lat)) {
updateGoogleMap(lat, lng, cityName);
}
// Update location details
document.getElementById('coordinates').textContent = `${lat.toFixed(2)}, ${lng.toFixed(2)}`;
// Fetch city details
fetchCityPopulation(cityName, lat, lng);
} else {
console.warn(`Geocoding failed for ${cityName}: ${status}`);
}
});
} catch (error) {
console.error("Error geocoding city:", error);
}
}
// Fetch city details using Google Geocoding API
async function fetchCityDetails(cityName, lat, lon) {
try {
// Using Google Geocoding API to get place details
const baseUrl = API_CONFIG.googleMaps.baseUrl;
const geocodeUrl = `${baseUrl}/geocode/json?latlng=${lat},${lon}&key=${API_CONFIG.googleMaps.key}`;
const response = await fetch(geocodeUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (data.status === 'OK' && data.results.length > 0) {
// Get formatted address
const result = data.results[0];
const formattedAddress = result.formatted_address;
// Update population field with formatted address
document.getElementById('population').textContent = formattedAddress || cityName;
console.log(`✅ City details fetched: ${formattedAddress}`);
} else {
document.getElementById('population').textContent = cityName;
}
} catch (error) {
console.error("❌ Error fetching city details:", error);
document.getElementById('population').textContent = cityName;
}
}
// ===== UPDATE JSON DISPLAY =====
function updateJSONDisplay() {
const jsonElement = document.getElementById('jsonData');
if (jsonElement) {
const allData = {
weather: weatherData || null,
airQuality: airQualityData || null
};
jsonElement.textContent = JSON.stringify(allData, null, 2);
}
}
// ===== GENERATE AI CITY DESCRIPTION WITH GEMINI =====
async function generateCityDescription(cityName, weatherData) {
try {
const descriptionElement = document.getElementById('cityDescription');
if (!descriptionElement) return;
// Show loading state
descriptionElement.innerHTML = '<p class="loading-text ai-generating">🤖 AI is analyzing the city... Generating insights...</p>';
// Get AQI value if available
let aqiInfo = "Air quality data loading...";
if (airQualityData) {
if (airQualityData.indexes) {
// Google AQI
const aqiIndex = airQualityData.indexes.find(idx => idx.code === 'uaqi') || airQualityData.indexes[0];
aqiInfo = `Current AQI: ${aqiIndex.aqi} (${aqiIndex.aqi <= 50 ? 'Good' : aqiIndex.aqi <= 100 ? 'Moderate' : 'Unhealthy'} air quality)`;
} else if (airQualityData.main) {
// OpenWeather AQI
const aqiMap = {1: "Excellent", 2: "Good", 3: "Moderate", 4: "Poor", 5: "Very Poor"};
aqiInfo = `Air quality: ${aqiMap[airQualityData.main.aqi]}`;
}
}
// Get location details from Google (if available)
const coordinates = `${weatherData.coord.lat.toFixed(4)}, ${weatherData.coord.lon.toFixed(4)}`;
const country = weatherData.sys.country || '';
// Create prompt for Gemini using Google Maps data
const prompt = `You are a smart city advisor helping people decide where to live, work, or study.
Analyze ${cityName}${country ? `, ${country}` : ''} and provide a comprehensive, engaging description (200-250 words) covering:
Current Real-Time Data:
- Temperature: ${Math.round(weatherData.main.temp)}°C
- Weather Condition: ${weatherData.weather[0].description}
- ${aqiInfo}
- Location Coordinates: ${coordinates}
- Humidity: ${weatherData.main.humidity}%
- Wind Speed: ${(weatherData.wind.speed * 3.6).toFixed(1)} km/h
Please provide:
1. **Smart City Rating**: How technologically advanced and smart is this city? (infrastructure, connectivity, innovation, digital services)
2. **For Students**: Education opportunities, universities, cost of living, student life, safety
3. **For Professionals**: Job market, industries, work culture, career growth, business opportunities
4. **Quality of Life**: Safety, healthcare, transportation, entertainment, culture, climate
5. **Why Choose This City**: Top 3 compelling reasons to move here based on current data