使用和风天气接口api(全过程)——获取天气

1、显示效果

2、注册和风天气的账号

和风天气的官网

和风天气插件 | 和风天气插件产品,免费、跨终端。适配你的网站、APP、公众号 (qweather.com)

3、获取和风天气的key

这个地方注意一下,看你是做案例还是,公司使用,如果是做案例,可以和小编一样选择免费订

阅。设置key的地方你可以选择Web API,如果你选择了 Android SDK / iOS SDK,那么生成的密

钥只能使用官方的 SDK 进行数据访问,如果是 Web API的话,可以自己编程获取并解析数据。

4、使用和风天气图标

npm i qweather-icons

5、移动图标


6、uniapp中使用

7、完整代码

<template>
	<view class="">
		<view class="header-modular" v-if="now">
			<image class="bg-wave" src="../../static/bg_wave.gif"></image>
			<view class="row">
				<view class="row location-wrap" @click="selectLocation">
					<view class="title">{{ City }} {{ County }}</view>
				</view>
			</view>
			<view class="row">
				<view class="tmp">{{ now.temp }}°</view>
				<image class="icon-weather" :src="`/static/icons/${now.icon}.svg`"></image>
			</view>
			<view class="tips-wrap">
				<view class="tips">{{ now.windDir }} {{ now.windScale }}级</view>
				<view class="tips">湿度 {{ now.humidity }}%</view>
				<view class="tips">气压 {{ now.pressure }}Pa</view>
			</view>
		</view>
		<!-- 24小时预报 -->
		<view class="card-modular" v-if="hourly">
			<view class="title">24小时预报</view>
			<view class="card-wrap">
				<block v-for="(item, index) in hourly" :key="index">
					<view class="item hourly">
						<view class="text-gray">{{ item.time }}</view>
						<image class="icon" :src="`/static/icons/${item.icon}.svg`"></image>
						<view class="text-primary mb-32">{{ item.temp }}°</view>
						<view>{{ item.windDir }}</view>
						<view class="text-gray">{{ item.windScale }}级</view>
					</view>
				</block>
			</view>
		</view>
		<!-- 7天预报 -->
		<view class="card-modular" v-if="daily">
			<view class="title">7天预报</view>
			<view class="card-wrap">
				<block v-for="(item, index) in daily" :key="index">
					<view class="item daily">
						<view>{{ item.dateToString }}</view>
						<view class="text-gray">{{ item.date }}</view>
						<view class="text-primary">{{ item.tempMin }}°~{{ item.tempMax }}°</view>
						<image class="icon" :src="`/static/icons/${item.iconDay}.svg`"></image>
						<view>{{ item.windDirDay }}</view>
						<view class="text-gray">{{ item.windScaleDay }}级</view>
					</view>
				</block>
			</view>
		</view>
	</view>
</template>

<script>
const APIKEY = ''; // 填入你申请的KEY

export default {
	data() {
		return {
			location: '',
			now: '',
			hourly: '',
			daily: '',
			City: '',
			County: ''
		};
	},
	onLoad() {
		this.getLocation();
	},
	methods: {
		//选择定位
		selectLocation() {
			var that = this;
			uni.chooseLocation({
				success(res) {
					that.location = res.longitude + ',' + res.latitude;
					that.getWeather();
					that.getCityByLoaction();
				},
				fail() {
					uni.getLocation({
						type: 'gcj02',
						fail() {
							uni.showModal({
								title: '获取地图位置失败',
								content:
									'为了给您提供准确的天气预报服务,请在设置中授权【位置信息】',
								success(mRes) {
									if (mRes.confirm) {
										uni.openSetting({
											success: function (data) {
												if (
													data.authSetting['scope.userLocation'] === true
												) {
													that.selectLocation();
												} else {
													uni.showToast({
														title: '授权失败',
														icon: 'none',
														duration: 1000
													});
												}
											},
											fail(err) {
												console.log(err);
												uni.showToast({
													title: '唤起设置页失败,请手动打开',
													icon: 'none',
													duration: 1000
												});
											}
										});
									}
								}
							});
						}
					});
				}
			});
		},
		/**
		 * 获取定位
		 */
		getLocation() {
			var that = this;
			uni.getLocation({
				type: 'gcj02',
				success(res) {
					that.location = res.longitude + ',' + res.latitude;
					that.getWeather();
					that.getCityByLoaction();
				},
				fail(err) {
					uni.showModal({
						title: '获取定位信息失败',
						content: '为了给您提供准确的天气预报服务,请在设置中授权【位置信息】',
						success(mRes) {
							if (mRes.confirm) {
								uni.openSetting({
									success: function (data) {
										if (data.authSetting['scope.userLocation'] === true) {
											uni.showToast({
												title: '授权成功',
												icon: 'success',
												duration: 1000
											});
											that.getLocation();
										} else {
											uni.showToast({
												title: '授权失败',
												icon: 'none',
												duration: 1000
											});
											that.location = '地理位置';
											that.getWeather();
											that.getCityByLoaction();
										}
									},
									fail(err) {
										console.log(err);
										uni.showToast({
											title: '唤起设置页失败,请手动打开',
											icon: 'none',
											duration: 1000
										});
										that.location = '地理位置';
										that.getWeather();
										that.getCityByLoaction();
									}
								});
							} else if (mRes.cancel) {
								that.location = '地理位置';
								that.getWeather();
								that.getCityByLoaction();
							}
						}
					});
				}
			});
		},
		/**
		 * 根据坐标获取城市信息
		 */
		getCityByLoaction() {
			var that = this;
			uni.request({
				url:
					'https://geoapi.qweather.com/v2/city/lookup?key=' +
					APIKEY +
					'&location=' +
					that.location,
				success(result) {
					var res = result.data;
					if (res.code == '200') {
						var data = res.location[0];
						that.City = data.adm2;
						that.County = data.name;
					} else {
						uni.showToast({
							title: '获取城市信息失败',
							icon: 'none'
						});
					}
				}
			});
		},
		/**
		 * 获取天气
		 */
		getWeather() {
			var that = this;
			uni.showLoading({
				title: '加载中'
			});
			uni.request({
				url:
					'https://devapi.qweather.com/v7/weather/now?key=' +
					APIKEY +
					'&location=' +
					that.location,
				success(result) {
					var res = result.data;
					that.now = res.now;
				}
			});
			uni.request({
				url:
					'https://devapi.qweather.com/v7/weather/24h?key=' +
					APIKEY +
					'&location=' +
					that.location,
				success(result) {
					var res = result.data;
					res.hourly.forEach(function (item) {
						item.time = that.formatTime(new Date(item.fxTime)).hourly;
					});
					that.hourly = res.hourly;
				}
			});
			uni.request({
				url:
					'https://devapi.qweather.com/v7/weather/7d?key=' +
					APIKEY +
					'&location=' +
					that.location,
				success(result) {
					var res = result.data;
					res.daily.forEach(function (item) {
						item.date = that.formatTime(new Date(item.fxDate)).daily;
						item.dateToString = that.formatTime(new Date(item.fxDate)).dailyToString;
					});
					that.daily = res.daily;
					uni.hideLoading();
				}
			});
		},
		// 格式时间
		formatTime(date) {
			const year = date.getFullYear();
			const month = date.getMonth() + 1;
			const day = date.getDate();
			const hour = date.getHours();
			const minute = date.getMinutes();
			const second = date.getSeconds();
			const weekArray = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
			const isToday = date.setHours(0, 0, 0, 0) == new Date().setHours(0, 0, 0, 0);
			return {
				hourly: [hour, minute].map(this.formatNumber).join(':'),
				daily: [month, day].map(this.formatNumber).join('-'),
				dailyToString: isToday ? '今天' : weekArray[date.getDay()]
			};
		},
		// 补零
		formatNumber(n) {
			n = n.toString();
			return n[1] ? n : '0' + n;
		}
	}
};
</script>

<style lang="scss">
.row {
	display: flex;
	align-items: center;
}

.mb-32 {
	margin-bottom: 32rpx;
}

/* 页面样式 */
.header-modular {
	height: 400rpx;
	background-color: #64c8fa;
	background: linear-gradient(to bottom, #56ccf2, #2f80ed);
	position: relative;
	padding: 30rpx;
}

.header-modular .bg-wave {
	width: 100vw;
	position: absolute;
	bottom: -2px;
	left: 0;
	right: 0;
	height: 120rpx;
	mix-blend-mode: screen;
}

.header-modular .location-wrap {
	color: #ffffff;
	font-weight: bold;
	font-size: 36rpx;
}

.header-modular .location-wrap .icon {
	width: 40rpx;
	height: 40rpx;
	margin-right: 8rpx;
}

.header-modular .tmp {
	font-size: 200rpx;
	/* font-weight: bold; */
	color: #ffffff;
	margin-right: auto;
}

.header-modular .icon-weather {
	width: 200rpx;
	height: 200rpx;
}

.header-modular .tips-wrap {
	display: flex;
	justify-content: space-between;
}

.header-modular .tips {
	font-size: 28rpx;
	opacity: 0.8;
	color: #ffffff;
	flex: 1;
}

.header-modular .tips:nth-child(3) {
	text-align: right;
}

.header-modular .tips:nth-child(2) {
	text-align: center;
}

.card-modular {
	padding: 0 30rpx;
	margin-top: 30rpx;
}

.card-modular > .title {
	font-size: 40rpx;
	font-weight: bold;
	position: relative;
	margin-left: 14rpx;
	margin-bottom: 16rpx;
}

.card-modular > .title::before {
	content: '';
	position: absolute;
	left: -14rpx;
	top: 10rpx;
	bottom: 10rpx;
	width: 8rpx;
	border-radius: 10rpx;
	background-color: #2f80ed;
}

.card-modular .card-wrap {
	width: 690rpx;
	border-radius: 18rpx;
	background-color: #ffffff;
	box-shadow: 0 0 20rpx 0 rgba(0, 0, 0, 0.2);
	overflow-x: auto;
	white-space: nowrap;
}

.card-modular .card-wrap .item {
	display: inline-flex;
	flex-direction: column;
	align-items: center;
	font-size: 28rpx;
	padding: 18rpx 0;
}
.card-modular .card-wrap .item.hourly {
	width: 138rpx;
}
.card-modular .card-wrap .item.daily {
	width: 172.5rpx;
}
.card-modular .card-wrap .item .icon {
	width: 60rpx;
	height: 60rpx;
	margin: 64rpx 0;
}

.card-modular .card-wrap .item .text-gray {
	color: gray;
}

.card-modular .card-wrap .item .text-primary {
	color: #2f80ed;
}
</style>

以下是使用和风天气API的C代码示例: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> #define MAX_CITY_NAME_LEN 100 #define MAX_WEATHER_LEN 2000 // 和风天气API的基本信息 #define API_KEY "your_api_key" //替换为你的API Key #define API_URL "https://free-api.heweather.net/s6/weather/now" // 回调函数,用于处理HTTP响应 size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata) { strcat((char *) userdata, ptr); // 将HTTP响应内容添加到userdata中 return size * nmemb; } int main() { // 从用户输入中获取城市名 char city[MAX_CITY_NAME_LEN]; printf("请输入城市名:"); scanf("%s", city); // 构造HTTP请求URL char url[MAX_WEATHER_LEN]; snprintf(url, MAX_WEATHER_LEN, "%s?key=%s&location=%s", API_URL, API_KEY, city); // 初始化CURL库和HTTP请求 CURL *curl = curl_easy_init(); if (!curl) { fprintf(stderr, "初始化CURL失败!\n"); return EXIT_FAILURE; } curl_easy_setopt(curl, CURLOPT_URL, url); // 设置HTTP请求URL curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); // 设置回调函数 char weather[MAX_WEATHER_LEN] = ""; // 用于存储HTTP响应内容的字符串 curl_easy_setopt(curl, CURLOPT_WRITEDATA, weather); // 设置回调函数的userdata // 执行HTTP请求 CURLcode res = curl_easy_perform(curl); if (res != CURLE_OK) { fprintf(stderr, "HTTP请求失败:%s\n", curl_easy_strerror(res)); return EXIT_FAILURE; } // 解析HTTP响应中的天气信息 char *status_start = strstr(weather, "\"status\":\""); // 找到状态码的起始位置 if (!status_start) { fprintf(stderr, "无法解析HTTP响应:%s\n", weather); return EXIT_FAILURE; } char *status_end = strchr(status_start + 11, '\"'); // 找到状态码的终止位置 if (!status_end) { fprintf(stderr, "无法解析HTTP响应:%s\n", weather); return EXIT_FAILURE; } *status_end = '\0'; // 将状态码终止位置的字符改为'\0',截断字符串 int status_code = atoi(status_start + 11); // 将状态码从字符串转换为整数 if (status_code != 200) { fprintf(stderr, "HTTP请求失败,状态码:%d\n", status_code); return EXIT_FAILURE; } char *cond_start = strstr(weather, "\"cond_txt\":\""); // 找到天气状况的起始位置 if (!cond_start) { fprintf(stderr, "无法解析HTTP响应:%s\n", weather); return EXIT_FAILURE; } char *cond_end = strchr(cond_start + 13, '\"'); // 找到天气状况的终止位置 if (!cond_end) { fprintf(stderr, "无法解析HTTP响应:%s\n", weather); return EXIT_FAILURE; } *cond_end = '\0'; // 将天气状况终止位置的字符改为'\0',截断字符串 char *cond_txt = cond_start + 13; // 天气状况的字符串就是起始位置的后面13个字符 printf("%s的天气状况为:%s\n", city, cond_txt); // 清理CURL库 curl_easy_cleanup(curl); return EXIT_SUCCESS; } ``` 需要注意的是,上述代码使用了libcurl库来进行HTTP请求,并使用了C标准库中的字符串处理函数来解析HTTP响应内容。在使用前需要安装libcurl库,并在编译时链接该库。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值