返回

打造你的天气小程序:和风天气API打造天气指南针

前端

使用微信小程序和和风天气 API 创建天气查询工具

简介

在炎炎夏日和寒冷冬日,及时了解天气状况至关重要。为了方便大家随时随地查询天气,本文将介绍如何使用微信小程序和和风天气 API 创建一个简洁的天气查询工具。

准备工作

1. 微信小程序账号注册

如果没有微信小程序账号,请前往微信小程序官方文档注册一个。

2. 微信开发者工具安装

微信开发者工具是开发微信小程序的必需工具,从微信小程序官网下载安装即可。

3. 和风天气 API 密钥获取

和风天气 API 提供天气数据。在和风天气官网注册账号后,即可获取 API 密钥。

创建微信小程序项目

1. 新建小程序项目

在微信开发者工具中,新建一个小程序项目。

2. 添加首页文件代码

在项目的 "pages/index/index.js" 文件中添加以下代码:

// ...代码...

3. 添加首页模板文件代码

在项目的 "pages/index/index.wxml" 文件中添加以下代码:

<!-- ...代码... -->

4. 添加首页样式文件代码

在项目的 "pages/index/index.wxss" 文件中添加以下代码:

/* ...代码... */

运行小程序

1. 运行真机调试

在微信开发者工具中,选择 "真机调试",并扫码登录微信小程序。

2. 输入城市查询天气

在小程序中,输入城市名称,点击 "查询" 按钮,即可获取该城市的天气信息。

代码示例

// "pages/index/index.js"
const app = getApp();

Page({
  data: {
    city: '北京',
    weather: {}
  },

  onLoad() {
    this.getWeather();
  },

  getWeather() {
    const that = this;
    wx.request({
      url: 'https://free-api.heweather.net/s6/weather/now',
      data: {
        location: this.data.city,
        key: '你的和风天气API密钥'
      },
      success(res) {
        that.setData({
          weather: res.data.HeWeather6[0].now
        })
      }
    })
  },

  bindCityInput(e) {
    this.setData({
      city: e.detail.value
    })
  },

  searchWeather() {
    this.getWeather();
  }
})
<!-- "pages/index/index.wxml" -->
<view class="container">
  <view class="search-box">
    <input type="text" placeholder="请输入城市名称" bindinput="bindCityInput" />
    <button type="primary" bindtap="searchWeather">查询</button>
  </view>
  <view class="weather-info">
    <view class="city">{{data.city}}</view>
    <view class="temp">{{data.weather.tmp}}</view>
    <view class="cond">{{data.weather.cond_txt}}</view>
  </view>
</view>
<!-- "pages/index/index.wxss" -->
.container { /* ...代码... */ }
.search-box { /* ...代码... */ }
.input { /* ...代码... */ }
.button { /* ...代码... */ }
.weather-info { /* ...代码... */ }
.city { /* ...代码... */ }
.temp { /* ...代码... */ }
.cond { /* ...代码... */ }

常见问题解答

1. 如何修改默认查询城市?

修改 "pages/index/index.js" 文件中的 "city" 变量值即可。

2. 如何更换和风天气 API 密钥?

修改 "pages/index/index.js" 文件中 "wx.request" 方法中 "key" 的值。

3. 天气信息不准确怎么办?

可能是和风天气 API 数据问题,或您的网络连接不稳定。

4. 小程序无法运行怎么办?

检查代码是否正确,并确保已正确安装微信开发者工具。

5. 如何优化小程序性能?

使用缓存和延迟加载等技术,减少 HTTP 请求次数,并使用轻量级 UI 元素。