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
| const weatherConfig = { key: 'YOUR_HEFENG_API_KEY', defaultLocation: '101010100', unit: 'c' };
const weatherIcons = { '100': '☀️', '101': '🌤️', '102': '⛅', '103': '☁️', '104': '🌫️', '200': '💨', '201': '🌬️', '202': '🌀', '203': '🌪️', '300': '🌧️', '301': '⛈️', '302': '🌩️', '303': '❄️', '304': '🌨️', '305': '🌦️', '306': '🌧️', '307': '🌧️', '308': '🌊', '309': '☔', '400': '❄️', '401': '❄️', '402': '❄️', '403': '❄️', '404': '🌨️', '405': '🌨️', '500': '🌫️', '501': '🌫️', '502': '🌫️', '503': '💨', '504': '💨', '507': '💨', '508': '💨' };
const weatherDescriptions = { '100': '晴', '101': '多云', '102': '少云', '103': '阴', '104': '雾', '200': '有风', '201': '平静', '202': '台风', '203': '龙卷风', '300': '雨', '301': '雷雨', '302': '雷暴', '303': '雪', '304': '雨夹雪', '305': '阵雨', '306': '大雨', '307': '暴雨', '308': '大暴雨', '309': '特大暴雨', '400': '小雪', '401': '中雪', '402': '大雪', '403': '暴雪', '404': '雨夹雪', '405': '阵雪', '500': '薄雾', '501': '雾', '502': '霾', '503': '扬沙', '504': '浮尘', '507': '沙尘暴', '508': '强沙尘暴' };
function getLocation() { return new Promise((resolve, reject) => { if (!navigator.geolocation) { reject(new Error('Geolocation not supported')); return; }
navigator.geolocation.getCurrentPosition( position => resolve(position), error => reject(error), { enableHighAccuracy: true, timeout: 5000 } ); }); }
async function getCityByLocation(lat, lon) { const url = `https://geoapi.qweather.com/v2/city/lookup?location=${lon},${lat}&key=${weatherConfig.key}`; try { const response = await fetch(url); const data = await response.json(); if (data.code === '200' && data.location && data.location.length > 0) { return data.location[0].id; } throw new Error('City not found'); } catch (error) { console.error('获取城市信息失败:', error); throw error; } }
async function fetchWeather(locationId) { const url = `https://devapi.qweather.com/v7/weather/now?location=${locationId}&key=${weatherConfig.key}`; try { const response = await fetch(url); const data = await response.json(); if (data.code === '200') { return data.now; } throw new Error(data.message || 'Weather data error'); } catch (error) { console.error('获取天气数据时出错:', error); throw error; } }
function updateWeatherWidget(weatherData) { const widget = document.getElementById('weatherWidget'); const weatherCode = weatherData.icon; const temp = weatherData.temp; const icon = weatherIcons[weatherCode] || '🌍'; const desc = weatherDescriptions[weatherCode] || '未知'; widget.innerHTML = ` <span class="weather-icon">${icon}</span> <span class="weather-temp">${temp}°${weatherConfig.unit.toUpperCase()}</span> <span class="weather-desc">${desc}</span> `; }
async function showDefaultWeather() { try { const weatherData = await fetchWeather(weatherConfig.defaultLocation); updateWeatherWidget(weatherData); } catch (error) { console.error('使用默认城市获取天气失败:', error); } }
async function initWeatherWidget() { try { const position = await getLocation(); const cityId = await getCityByLocation(position.coords.latitude, position.coords.longitude); const weatherData = await fetchWeather(cityId); updateWeatherWidget(weatherData); localStorage.setItem('lastKnownCity', cityId); } catch (error) { console.log('自动定位失败,使用默认城市:', error); const lastKnownCity = localStorage.getItem('lastKnownCity'); if (lastKnownCity) { try { const weatherData = await fetchWeather(lastKnownCity); updateWeatherWidget(weatherData); return; } catch (e) { console.error('使用上次城市获取天气失败:', e); } } showDefaultWeather(); } setInterval(async () => { const lastKnownCity = localStorage.getItem('lastKnownCity') || weatherConfig.defaultLocation; try { const weatherData = await fetchWeather(lastKnownCity); updateWeatherWidget(weatherData); } catch (error) { console.error('定时更新天气失败:', error); } }, 3600000); }
document.addEventListener('DOMContentLoaded', initWeatherWidget);
|