創建應用獲取 ?Key
天氣查詢-基礎 API 文檔-開發指南-Web服務 API | 高德地圖API
代碼編寫
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>天氣查詢</title><style>* {margin: 0;padding: 0;box-sizing: border-box;}body {font-family: 'Microsoft YaHei', sans-serif;background: linear-gradient(to bottom, #87CEEB, #1E90FF);height: 100vh;display: flex;justify-content: center;align-items: center;}.container {width: 90%;max-width: 500px;background-color: rgba(255, 255, 255, 0.8);border-radius: 10px;padding: 20px;box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);}h1 {text-align: center;margin-bottom: 20px;color: #333;}.search-box {display: flex;gap: 10px;margin-bottom: 20px;}.location-select {flex: 1;padding: 10px;border: 1px solid #ddd;border-radius: 5px;font-size: 16px;}#search-btn {padding: 10px 20px;border-radius: 5px;}.weather-info {display: none;padding: 15px;background-color: white;border-radius: 5px;box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);margin-top: 20px;}.weather-info h2 {color: #1E90FF;text-align: center;margin-bottom: 15px;}.weather-details {display: grid;grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));gap: 15px;padding: 10px;}.weather-item {background-color: #f5f5f5;border-radius: 8px;padding: 15px;text-align: center;box-shadow: 0 2px 4px rgba(0,0,0,0.1);}.weather-item h3 {color: #333;font-size: 14px;margin-bottom: 8px;}.weather-item p {color: #666;font-size: 16px;font-weight: bold;}.error-message {color: red;text-align: center;margin-top: 10px;display: none;}</style><script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
</head>
<body><div class="container"><h1>天氣查詢</h1><div class="search-box"><select id="province-select" class="location-select"><option value="">請選擇省份</option></select><select id="city-select" class="location-select" disabled><option value="">請選擇城市</option></select><select id="district-select" class="location-select" disabled><option value="">請選擇區縣</option></select><button id="search-btn">查詢</button></div><div id="error-message" class="error-message"></div><div id="weather-info" class="weather-info"><h2 id="city-name"></h2><div class="weather-details"><div class="weather-item"><h3>天氣現象</h3><p id="weather-desc"></p></div><div class="weather-item"><h3>實時溫度</h3><p id="temperature"></p></div><div class="weather-item"><h3>空氣濕度</h3><p id="humidity"></p></div><div class="weather-item"><h3>風向</h3><p id="wind-direction"></p></div><div class="weather-item"><h3>風力級別</h3><p id="wind-speed"></p></div><div class="weather-item"><h3>數據發布時間</h3><p id="report-time"></p></div></div></div></div><script>document.addEventListener('DOMContentLoaded', function() {const searchBtn = document.getElementById('search-btn');const weatherInfo = document.getElementById('weather-info');const errorMessage = document.getElementById('error-message');const cityName = document.getElementById('city-name');const weatherDesc = document.getElementById('weather-desc');const temperature = document.getElementById('temperature');const humidity = document.getElementById('humidity');const windSpeed = document.getElementById('wind-speed');// 使用高德地圖API,替換為您的密鑰 // https://console.amap.com/dev/key/appconst API_KEY = '';// 省份和城市數據let provinces = [];let citiesByProvince = {};let districtsByCity = {};let areaCodeMap = {};// 加載并解析xlsx文件async function loadCityData() {try {const response = await fetch('AMap_adcode_citycode.xlsx');const arrayBuffer = await response.arrayBuffer();const data = new Uint8Array(arrayBuffer);const workbook = XLSX.read(data, {type: 'array'});const worksheet = workbook.Sheets[workbook.SheetNames[0]];const jsonData = XLSX.utils.sheet_to_json(worksheet);// 處理數據jsonData.forEach(row => {const name = row['中文名'] || '';const code = String(row['adcode'] || '');if (name && code) {// 添加到區域編碼映射areaCodeMap[name] = code;if (code.endsWith('0000')) {// 處理直轄市和省份const isDirectCity = ['北京市', '上海市', '天津市', '重慶市'].includes(name);if (isDirectCity) {// 直轄市作為城市處理const province = name.substring(0, 2); // 去掉"市"字if (!provinces.includes(province)) {provinces.push(province);citiesByProvince[province] = [name];}// 初始化直轄市的區縣數組districtsByCity[name] = [];} else {// 普通省份provinces.push(name);citiesByProvince[name] = [];}} else if (code.endsWith('00')) {// 市級const provinceCode = code.substring(0, 2) + '0000';const province = jsonData.find(item => String(item['adcode']) === provinceCode)?.['中文名'];if (province) {const provinceName = province.endsWith('市') ? province.substring(0, 2) : province;if (!citiesByProvince[provinceName]) {citiesByProvince[provinceName] = [];}if (!citiesByProvince[provinceName].includes(name)) {citiesByProvince[provinceName].push(name);}districtsByCity[name] = [];}} else {// 區縣級const cityCode = code.substring(0, 4) + '00';const city = jsonData.find(item => String(item['adcode']) === cityCode)?.['中文名'];// 處理直轄市的區縣const provinceCode = code.substring(0, 2) + '0000';const province = jsonData.find(item => String(item['adcode']) === provinceCode)?.['中文名'];if (province && ['北京市', '上海市', '天津市', '重慶市'].includes(province)) {// 直轄市的區縣直接添加到市級if (districtsByCity[province]) {districtsByCity[province].push(name);}} else if (city && districtsByCity[city]) {// 普通城市的區縣districtsByCity[city].push(name);}}}});// 初始化下拉框populateProvinceSelect();console.log('城市數據加載完成');} catch (error) {console.error('加載城市數據失敗:', error);showError('加載城市數據失敗');}}// 填充省份下拉框function populateProvinceSelect() {const provinceSelect = document.getElementById('province-select');const citySelect = document.getElementById('city-select');const districtSelect = document.getElementById('district-select');// 清空所有選擇provinceSelect.innerHTML = '<option value="">請選擇省份</option>';resetCitySelect();resetDistrictSelect();provinces.sort().forEach(province => {const option = document.createElement('option');option.value = province;option.textContent = province;provinceSelect.appendChild(option);});// 監聽省份選擇變化provinceSelect.addEventListener('change', function() {const selectedProvince = this.value;if (selectedProvince) {populateCitySelect(selectedProvince);// 直轄市不需要在省級查詢天氣if (!['北京', '上海', '天津', '重慶'].includes(selectedProvince)) {fetchWeather(selectedProvince);}} else {resetCitySelect();resetDistrictSelect();}});}// 填充城市下拉框function populateCitySelect(province) {const citySelect = document.getElementById('city-select');// 清空城市和區縣選擇resetCitySelect();resetDistrictSelect();citySelect.disabled = false;citiesByProvince[province].sort().forEach(city => {const option = document.createElement('option');option.value = city;option.textContent = city;citySelect.appendChild(option);});// 如果是直轄市,自動選擇第一個城市if (['北京', '上海', '天津', '重慶'].includes(province) && citiesByProvince[province].length > 0) {citySelect.value = citiesByProvince[province][0];const selectedCity = citySelect.value;if (selectedCity) {populateDistrictSelect(selectedCity);fetchWeather(selectedCity);}}// 監聽城市選擇變化citySelect.addEventListener('change', function() {const selectedCity = this.value;if (selectedCity) {populateDistrictSelect(selectedCity);fetchWeather(selectedCity);} else {resetDistrictSelect();}});}// 添加區縣選擇處理function populateDistrictSelect(city) {const districtSelect = document.getElementById('district-select');// 清空區縣選擇resetDistrictSelect();if (districtsByCity[city] && districtsByCity[city].length > 0) {districtSelect.disabled = false;districtsByCity[city].sort().forEach(district => {const option = document.createElement('option');option.value = district;option.textContent = district;districtSelect.appendChild(option);});}// 監聽區縣選擇變化districtSelect.addEventListener('change', function() {const selectedDistrict = this.value;if (selectedDistrict) {fetchWeather(selectedDistrict);}});}// 添加重置函數function resetCitySelect() {const citySelect = document.getElementById('city-select');citySelect.innerHTML = '<option value="">請選擇城市</option>';citySelect.disabled = true;}function resetDistrictSelect() {const districtSelect = document.getElementById('district-select');districtSelect.innerHTML = '<option value="">請選擇區縣</option>';districtSelect.disabled = true;}// 修改天氣查詢函數function fetchWeather(area) {weatherInfo.style.display = 'none';errorMessage.style.display = 'none';searchBtn.disabled = true;searchBtn.textContent = '查詢中...';const areaCode = areaCodeMap[area];if (!areaCode) {showError('未找到該地區的編碼');searchBtn.disabled = false;searchBtn.textContent = '查詢';return;}const weatherUrl = `https://restapi.amap.com/v3/weather/weatherInfo?city=${areaCode}&key=${API_KEY}`;fetch(weatherUrl).then(response => response.json()).then(data => {if (data.status === '1' && data.lives && data.lives.length > 0) {displayWeather(data, area);} else {showError('未找到天氣信息');}}).catch(error => {showError('查詢失敗: ' + error.message);console.error('Error:', error);}).finally(() => {searchBtn.disabled = false;searchBtn.textContent = '查詢';});}// 更新查詢按鈕事件監聽document.addEventListener('click', function(e) {if (e.target && e.target.id === 'search-btn') {const citySelect = document.getElementById('city-select');const selectedCity = citySelect.value;if (!selectedCity) {showError('請選擇城市');return;}fetchWeather(selectedCity);}});// 初始化loadCityData();function updateWeatherInfo() {const weatherDetails = document.querySelector('.weather-details');weatherDetails.innerHTML = `<div class="weather-item"><h3>天氣現象</h3><p id="weather-desc"></p></div><div class="weather-item"><h3>實時溫度</h3><p id="temperature"></p></div><div class="weather-item"><h3>空氣濕度</h3><p id="humidity"></p></div><div class="weather-item"><h3>風向</h3><p id="wind-direction"></p></div><div class="weather-item"><h3>風力級別</h3><p id="wind-speed"></p></div><div class="weather-item"><h3>數據發布時間</h3><p id="report-time"></p></div>`;}function displayWeather(data, city) {const weatherData = data.lives[0];console.log('天氣數據:', weatherData); // 調試用// 更新城市名稱cityName.textContent = weatherData.city || city;// 更新所有天氣信息document.getElementById('weather-desc').textContent = weatherData.weather || '未知';document.getElementById('temperature').textContent = `${weatherData.temperature || '--'}°C`;document.getElementById('humidity').textContent = `${weatherData.humidity || '--'}%`;document.getElementById('wind-direction').textContent = weatherData.winddirection || '未知';document.getElementById('wind-speed').textContent = `${weatherData.windpower || '--'} 級`;// 格式化并顯示發布時間const reportTime = weatherData.reporttime || '';const formattedTime = reportTime ? new Date(reportTime).toLocaleString('zh-CN') : '未知';document.getElementById('report-time').textContent = formattedTime;// 顯示天氣信息區域weatherInfo.style.display = 'block';}function showError(message) {errorMessage.textContent = message;errorMessage.style.display = 'block';weatherInfo.style.display = 'none';}// 更新天氣信息展示區域updateWeatherInfo();});</script>
</body>
</html>
效果實現
項目地址
https://github.com/R-K05/weather_inquiry