使用高德api實現天氣查詢

創建應用獲取 ?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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/75580.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/75580.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/75580.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

XEOS 與 AutoMQ 推出聯合方案,共筑云原生 Kafka 新生態

近日&#xff0c;XSKY 星辰天合旗下企業級對象存儲產品 XEOS 與 AutoMQ 云原生消息隊列系統完成了產品兼容性適配互認證&#xff0c;致力于為客戶在私有云和混合云環境中提供云原生的 Kafka 解決方案。 在云計算和大數據時代&#xff0c;消息隊列作為分布式系統的重要組成部分…

Synology NAS 部署WPS-Office

記錄在群暉NAS上部署WPS-Office實現網頁上編輯文檔 目錄 1.思考及想法由來2.問題解決2.1 群暉NAS Docker使用2.2 部署wps-office參考1:【Docker+WPS Office】遠程辦公:Docker + WPS Office 私人云辦公室2.3 群暉NAS映射文件夾權限參考1:參考2:群暉NAS中普通用戶獲取Docker容…

Vue自定義指令最佳實踐教程

Vue 3 顯著增強了自定義指令的功能&#xff0c;使其封裝更加靈活和易用。本文將分為基礎和進階兩部分&#xff0c;介紹如何實現常用的自定義指令&#xff0c;并提供最佳的項目組織方式。 前言 本文以復制文本的自定義指令詳細介紹自定義指令的基礎知識 多個自定義指令如何進行…

用DrissionPage升級維基百科爬蟲:更簡潔高效的數據抓取方案

一、原方案痛點分析 原代碼使用urllibBeautifulSoup組合存在以下問題&#xff1a; 動態內容缺失&#xff1a;無法獲取JavaScript渲染后的頁面內容 反爬能力弱&#xff1a;基礎請求頭易被識別為爬蟲 代碼冗余&#xff1a;需要單獨處理SSL證書驗證 擴展性差&#xff1a;難以應…

23種設計模式-結構型模式-代理

文章目錄 簡介問題解決方案代碼核心設計要點 總結 簡介 代理是一種結構型設計模式&#xff0c;讓你能夠提供對象的替代品或其占位符。代理控制著對于原對象的訪問&#xff0c;并允許在把請求提交給對象前后進行一些處理。 問題 為什么要控制對于某個對象的訪問呢&#xff1f…

基于Transformer框架實現微調后Qwen/DeepSeek模型的非流式批量推理

在基于LLamaFactory微調完具備思維鏈的DeepSeek模型之后(詳見《深入探究LLamaFactory推理DeepSeek蒸餾模型時無法展示<think>思考過程的問題》),接下來就需要針對微調好的模型或者是原始模型(注意需要有一個本地的模型文件,全量微調就是saves下面的文件夾,如果是LoRA,…

基于OpenCV的指紋驗證:從原理到實戰的深度解析

指紋識別的技術革命與OpenCV的輕量級方案 在生物特征識別領域&#xff0c;指紋識別始終以獨特性和穩定性占據核心地位。隨著OpenCV等開源視覺庫的普及&#xff0c;這項看似"高大上"的技術正逐步走向民用化開發。本文將突破傳統算法框架&#xff0c;提出一套基于OpenC…

十五屆藍橋杯省賽Java B組(持續更新..)

目錄 十五屆藍橋杯省賽Java B組第一題&#xff1a;報數第二題&#xff1a;類斐波那契數第三題&#xff1a;分布式隊列第四題&#xff1a;食堂第五題&#xff1a;最優分組第六題&#xff1a;星際旅行第七題&#xff1a;LITS游戲第八題&#xff1a;拼十字 十五屆藍橋杯省賽Java B…

多模態學習(八):2022 TPAMI——U2Fusion: A Unified Unsupervised Image Fusion Network

論文鏈接&#xff1a;https://ieeexplore.ieee.org/stamp/stamp.jsp?tp&arnumber9151265 目錄 一.摘要 1.1 摘要翻譯 1.2 摘要解析 二.Introduction 2.1 Introduciton翻譯 2.2 Introduction 解析 三. related work 3.1 related work翻譯 3.2 relate work解析 四…

電腦屏幕亮度隨心控,在Windows上自由調整屏幕亮度的方法

調整電腦屏幕的亮度對于保護視力和適應不同環境光線條件非常重要。無論是在白天強光下還是夜晚昏暗環境中&#xff0c;合適的屏幕亮度都能讓您的眼睛更加舒適。本文中簡鹿辦公小編將向您介紹幾種在 Windows 系統中調整屏幕亮度的方法。 方法一&#xff1a;使用快捷鍵 大多數筆…

AF3 OpenFoldDataset類looped_samples方法解讀

AlphaFold3 data_modules 模塊的 OpenFoldDataset 類的 looped_samples 方法用于 循環采樣數據,確保數據能被不斷地提供,適用于 PyTorch 的 DataLoader 在訓練過程中迭代讀取數據。dataset_idx 指定了當前要處理的數據集(即 self.datasets[dataset_idx]) 源代碼: def loo…

lua表table和JSON字符串互轉

--print("local ssxc{\n"..string.gsub(str,":","").."\n}") Utils {} ---------------------------------------------------------------------------------- -- Lua-Table 與 string 轉換 local function value2string(value, isA…

請談談分治算法,如何應用分治算法解決大規模問題?

分治算法實戰解析與前端應用指南 分治算法本質剖析 分治算法的核心在于"分而治之"&#xff0c;其工作流程可分解為三個關鍵階段&#xff1a; 分解階段&#xff08;Divide&#xff09;&#xff1a;將復雜問題拆分為若干個相互獨立的子問題攻克階段&#xff08;Conqu…

基于BusyBox構建ISO鏡像

1. 準備 CentOS 7.9 3.10.0-957.el7.x86_64VMware Workstation 建議&#xff1a;系統內核<3.10.0 使用busybox < 1.33.2版本 2. 安裝busybox # 安裝依賴 yum install syslinux xorriso kernel-devel kernel-headers glibc-static ncurses-devel -y# 下載 wget https://…

Node.js 與 MySQL:深入理解與高效實踐

Node.js 與 MySQL:深入理解與高效實踐 引言 隨著互聯網技術的飛速發展,Node.js 作為一種高性能的服務端JavaScript運行環境,因其輕量級、單線程和事件驅動等特點,受到了廣大開發者的青睞。MySQL 作為一款開源的關系型數據庫管理系統,以其穩定性和可靠性著稱。本文將深入…

Android學習總結之handler源碼級

一、核心類關系與線程綁定&#xff08;ThreadLocal 的核心作用&#xff09; 1. Looper 與 ThreadLocal 的綁定 每個線程的 Looper 實例通過 ThreadLocal<Looper> sThreadLocal 存儲&#xff0c;確保線程隔離&#xff1a; public final class Looper {// 線程本地存儲&…

群體智能優化算法-算術優化算法(Arithmetic Optimization Algorithm, AOA,含Matlab源代碼)

摘要 算術優化算法&#xff08;Arithmetic Optimization Algorithm, AOA&#xff09;是一種新穎的群體智能優化算法&#xff0c;靈感來源于加、減、乘、除四種基本算術運算。在優化過程中&#xff0c;AOA 通過乘除操作實現全局探索&#xff0c;通過加減操作強化局部開發&#…

廣告推薦算法:COSMO算法與A9算法的對比

COSMO算法與A9算法的概念解析 1. A9算法 定義與背景&#xff1a; A9算法是亞馬遜早期為電商平臺研發的核心搜索算法&#xff0c;主要用于優化商品搜索結果的排序和推薦&#xff0c;其核心邏輯圍繞產品屬性與關鍵詞匹配展開。自2003年推出以來&#xff0c;A9通過分析商品標題…

EasyExcel 數據字典轉換器實戰:注解驅動設計

一、場景痛點與解決方案 1. 問題背景 在 Excel 導入導出場景中&#xff0c;開發者常面臨以下問題&#xff1a; 數據可讀性差&#xff1a;數據庫存儲的字典值&#xff08;如 1、true&#xff09;直接導出時難以理解雙向轉換復雜&#xff1a;導入時需將用戶輸入的標簽反向解析…

五種音頻器件綜合對比——《器件手冊--音頻器件》

目錄 音頻器件 簡述 1. 揚聲器&#xff08;Speakers&#xff09; 2. 麥克風&#xff08;Microphones&#xff09; 3. 放大器&#xff08;Amplifiers&#xff09; 4. 音頻接口&#xff08;Audio Interfaces&#xff09; 5. 音頻處理器&#xff08;Audio Processors&#xff09…