使用高德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.mzph.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…