微信小程序获取和风天气API
1. 浏览器搜索微信小程序开发者工具并下载


2. 创建项目
AppID注册或使用测试号都可以,测试号申请一下即可。
后端服务选择不使用云服务。模板选择JS基础模板。点击创建。


3. 基础编写
1)导航栏更改
点击app.json文件


打开微信官方文档。
可以通过修改window属性来修改全局界面。


根据微信文档可知,
navigationBarTextStyle是导航栏标题的颜色属性
navigationBarTitleText是导航栏标题的内容属性
navigationBarBackgroundColor是导航栏背景的颜色属性
这里我将导航栏标题的颜色属性改成白色,导航栏标题的内容属性改成“当地天气获取”,导航栏背景的颜色属性改成蓝色。
修改前:

修改后:

点击正上方编译

编译结果如图:

2)组件了解
打开pages/index/index.wxml文件

打开微信官方文档
可以和文档中的组件一一对应,了解其功能。

3)清空内容,开始编写

根据自己想要的页面布局分别配置index.wxml文件和index.wxss。
这里我配置了三个变量,分别是位置、温度和天气类型,为了美观,简单添加了容器的外观样式和三张矢量图片。
效果如左侧显示


若编译后左侧界面显示无变化,重启软件。
4. 小程序定位
打开微信官方文档,找到wx.getLocation

下滑找到示例代码,复制代码至index.js

将获取的结果打印出来

然后打开app.json文件,配置代码获取定位权限


编译运行后获得当前设备位置的经纬度

5. 获取和风天气URL
1) 搜索和风天气

在和风天气里注册账号并打开控制台

在项目管理中创建项目

创建凭据

这个KEY后续会用到


2) 利用和风天气城市搜索API获取当前城市定位
打开和风天气开发文档,点击城市搜索

下拉找到请求示例,复制粘贴到index.js

Your_api_host在开发者信息里可以查询,每个人的都是不一样的。


粘贴后点击编译,出现下面报错信息

在右上角详情的本地设置里勾选不校验合法域名

再次编译,得到当前设备所在位置信息


获取位置成功后就可以更新变量了。

继续获取天气,回到和风天气开发文档,点击实时天气for API。

与之前同样的步骤,找到请求示例

复制粘贴到index.js文件,当前天气状况如图。

更新变量

index.js文件
点击查看代码
// index.js
Page({
data:{
temp:'-',
local:'-',
type:'-',
},
onLoad() {
this.getweather()
},
//获取天气
getweather(e){
let that=this
wx.getLocation({
type: 'wgs84',
success (res) {
console.log(res);
const latitude = res.latitude
const longitude = res.longitude
const key = '6a46848d1cfc4199bde4dabd90307569'
wx.request({
url: `https://k4564ub38n.re.qweatherapi.com/geo/v2/city/lookup?location=${longitude},${latitude}&key=${key}`,
success(res){
that.setData({
local:res.data.location[0].name
})
wx.request({
url: `https://k4564ub38n.re.qweatherapi.com/v7/weather/now?location=${longitude},${latitude}&key=${key}`,
success(res){
console.log(res);
that.setData({
temp:res.data.now.temp,
type:res.data.now.text
})
}
})
}
})
}
})
}
})
index.wxml文件
点击查看代码
<view class="container">
<view class="body">
<view class="body-wrapper">
<view class="data">
<view class="data-logo">
<image src="/pages/picture/dingwei.png" />
</view>
<view class="data-text">
<view>位置:{{local}}</view>
</view>
</view>
<view class="data">
<view class="data-logo">
<image src="/pages/picture/wendu.png" />
</view>
<view class="data-text">
<view>温度:{{temp}}℃</view>
</view>
</view>
</view>
<view class="data">
<view class="data-logo">
<image src="/pages/picture/tianqi.png" />
</view>
<view class="data-text">
<view>天气类型:{{type}}</view>
</view>
</view>
</view>
</view>
index.wxss文件
点击查看代码
.container{
padding:15rpx;
}
/*body*/
.body-wrapper{
margin-top: 40rpx;
display: flex;
flex-direction: column;
gap: 20rpx;
align-items: center;
}
.data-logo image{
width: 107rpx;
height: 107rpx;
}
.data{
display: flex;
justify-content: space-around;
background-color: #fff;
width: 600rpx;
height: 160rpx;
border-radius: 40rpx;
box-shadow: #77778a 0 0 10rpx;
padding: 10px;
margin-bottom: 23px;
}
.data-logo{
display: flex;
align-items: center;
}
.data-text{
display: flex;
flex-direction: column;
justify-content: space-around;
font-size: 40rpx;
}
浙公网安备 33010602011771号