微信小程序之天气查询小案例

本次小项目是关于微信小程序-动态查询天气(墨迹天气Api)

此次案例分为以下几个准备方面:

一.准备方面:

(1)如何发起请求?查看文档:RequestTask | 微信开放文档

(2)如何获取定位信息?查看文档:wx.getLocation(Object object) | 微信开放文档

(3)如何控制页面来实现数据实时渲染?查看文档:Page | 微信开放文档

(4)WXML语法条件参考:WXML | 微信开放文档

(5)墨迹天气api提供:https://autodev.openspeech.cn/csp/api/v2.1/weather

(6)对微信开发者工具的设置:查看下图:

 

二.当前页面的js代码解析(从内向外解析):

定义第一个函数,向墨迹天气api发起请求,并获取天气数据

>形参:location-存放定位信息(经纬度),city-查询的城市,sFun-请求成功的回调函数

 //获取天气(含api)
 function sendtemp(location, city, sFun) {
    //测试
    console.log(`https://autodev.openspeech.cn/csp/api/v2.1/weather?${city == ""?"":'city='+city+"&"}${location.latitude == ""?"":"latitude="+location.latitude+"&"}${location.longitude == ""?"":"longitude="+location.longitude+"&"}clientType=android&openId=aiuicus&sign=android`);

    //获取墨迹天气api
    wx.request({
      url: `https://autodev.openspeech.cn/csp/api/v2.1/weather?${city == ""?"":'city='+city+"&"}${location.latitude == ""?"":"latitude="+location.latitude+"&"}${location.longitude == ""?"":"longitude="+location.longitude+"&"}clientType=android&openId=aiuicus&sign=android`,
      success: result => sFun(result),
      header: {
        'content-type': 'application/json' // 默认值
      },
      fail: (err) => {},
      complete: (res) => {},
    })
  }

 定义第二个函数来判断获取天气的方式,并且船舰location对象

>形参:city-查询的城市

作用:如果city为空串,则获取定位查询天气,如果是含有城市名称的字符串,则直接查询天气.

sFun-依然是获取墨迹天气api的成功回调函数

 //判断获取天气的方式(判断是否定位获取?)
  function getWeather(city, sFun) {
    //测试
    console.log(city);
    //创建定位对象
    var location = {
      latitude: "", //纬度
      longitude: "" //经度
    };
    if (city == "") {
      //当没有查询天气则定位获取 or 当查询城市为空时则采取定位获取
      wx.getLocation({
        type: "wgs84",
        success(res) {
          location = res;
          sendtemp(location, city, sFun);
        }
      })
    } else {
      //查询城市天气
      sendtemp(location, city, sFun);
    }
    
  }

 Page对象的设置:

(1)当页面加载时(onload),触发定位获取天气的函数,传入空串的city,以及获取天气成功时的回调函数,也就是上两个函数的sFun,sFun这里的形参result实际上就是获取天气成功之后的数据对象.

---在这里定义sFun的函数,可提高代码的复用性,遵循了高内聚低耦合,大大减少了代码量.

(2)定义表单的提交时的函数:传入带有值或空串的city,回调函数跟之前的一样,如果有特殊的要求,还可以自由改变函数里的代码

--可能有些人会疑问为什么这里不再定义一个函数,来重复使用,提高代码复用性呢?

答:如果要重新定义一个函数,那么在以上每个函数的形参中我们都要传入一个this(这里指的是page本身),用$this来接收,然后在调用回调函数时,把$this传入才可以提高我们的代码复用性,也就是说this要绕一大圈才可以在回调函数中使用,作者认为这样的方式有点奇怪就没有再次提高代码的复用性,如果读者觉得不麻烦的话,其实也可以使用这样的方式.

  Page({

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      getWeather("", result => {
        if(result.data.code === 0){
          //code为0时,代表有查询的天气数据
          var res = result.data.data.list[0];
          this.setData({
            code: result.data.code, //用于条件判断
            list: result.data.data.list, //天气列表
            todayWeather: res, //今日天气
          })
        }
      });
    },
    /*
     表单的查询天气函数
    */
    search: function (e) {
      getWeather(e.detail.value.city, result => {
        //code为0时,代表有查询的天气数据
        if(result.data.code === 0){
          var res = result.data.data.list[0];
          this.setData({
            code: result.data.code, //用于条件判断
            list: result.data.data.list, //天气列表
            todayWeather: res, //今日天气
          })
        }
      });
    },
  })

三.这个内容就不做解析了,相信大家学习到这里已经有牢固的前端知识基础了.

(1)wxml:这里多了一些条件渲染还有表单使用的区别,大家可以查看以下两个文档了解一下就可以了

条件渲染:条件渲染 | 微信开放文档

列表渲染:列表渲染 | 微信开放文档

表单使用:form | 微信开放文档

<image src="../../images/beijing.jpeg" class="bg-image"/>
<view class="search">
  <form bindsubmit="search">
    <input type="text" name="city" placeholder="请输入城市"/>
    <button form-type="submit" type="primary" size="mini">查询天气</button>
  </form>
</view>
<view class="main">
  <view class="info" wx:if="{{code===0}}">
    <view class="temp">{{todayWeather.high}}℃</view>
    <view class="lowhigh">空气质量 {{todayWeather.airQuality}}</view>
    <view class="type">{{todayWeather.weather}}</view>
    <view class="city">{{todayWeather.province}} {{todayWeather.city}}
    </view>
    <view class="week">
      {{todayWeather.date}}
    </view>
    <view class="weather">
      {{ todayWeather.wind }}
    </view>
  </view>
</view>
<scroll-view class="list" scroll-x wx:if="{{code===0}}">
  <block wx:for="{{list}}" wx:key="index">
    <view class="item">
      <view>{{item.weather}}</view>
      <view>{{item.high}}℃/{{item.low}}℃</view>
      <view>{{item.date}}</view>
      <view>{{item.airQuality}}</view>
      <view>{{item.wind}}</view>
    </view>
  </block>
</scroll-view>

下附背景图(有水印,作者也没办法去掉.大家如果不想使用的话,可以直接删除含有背景的代码即可.)

背景图

(2)wxss: 

.main {
  display: flex;
  width: 100%;
  justify-content: center;
  text-align: center;
  margin-top: 20px;
}
.info view{
  margin-top: 10px;
  font-weight: 300;
}
.info .temp{
  font-weight: 400;
  font-size: 64px;
}
.info .lowhigh{
  font-size: 8px;
}
.info .type{
  font-size: 14px;
}
.info .city{
  font-weight: bold;
}
.info .week,.weather{
  font-size: 10px;
}
.search{
  display: flex;
  padding-top: 50rpx;
  justify-content: center;
}
.search form input{
  display: inline-block;
  border: 1px solid gray;
  height: 60rpx;
  margin-right: 10rpx;
  padding-left: 10rpx;
  border-radius: 10rpx;
}
.search form button{
  display: inline-block;
}

.list{
  margin-top: 100rpx;
  width: 100%;
  padding-top: 100rpx;
  border-top: 1px solid #cccccc;
  white-space: nowrap;
}

.item{
  display: inline-block;
  width: 30%;
  margin-right: 10rpx;
  text-align: center;
  font-size: 14px;
  line-height: 25px;
  font-family: "微软雅黑";
}
.bg-image{
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: -999;
}

(3)代码的演示:

初步加载时触发

查询天气时触发

(4)预览时有问题可看:微信小程序预览(真机调试)时请求获取不到API数据的解决方案

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程搬砖我最强

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值