微信小程序之天气预报

版权声明:本文为博主原创文章,指明出处即可任意转载。 https://blog.csdn.net/Inite/article/details/74906945

      入门小程序之后跟着视频做了一个简易版的“天气预报”,在手机运行的话能准确定位所在城市并查询到相应的天气状况,页面就一个,功能也不复杂,主要调用了百度地图api查询所在位置和和天气api根据城市查询天气。效果图如下:


目录结构如下:


 注册完百度地图api之后直接登录创建应用,如下图所示:



 百度:https://www.heweather.com 之后注册登录后点击右上角的控制台获取个人认证key。再到API文档查看调用方法:

付费用户:https://api.heweather.com/v5/forecast?city=yourcity&key=yourkey

免费用户:https://free-api.heweather.com/v5/forecast?city=yourcity&key=yourkey

 

 准备工作做好之后直接开始布局首页,可以参考下图:

 

  个人感觉样式得多写,多尝试,还是比较“恶心”的,调样式!

  app.json 文件代码如下:

  

{
  "pages":[
    "pages/index/index"
  ],
  "window":{
    "backgroundTextStyle":"light",
    "navigationBarBackgroundColor": "#019CCA",
    "navigationBarTitleText": "Weather Report",
    "navigationBarTextStyle":"#fff"
  }
}

  index.wxml 文件代码如下:

<!--index.wxml-->
<image class="bg" mode="aspectFill" src="../../icons/day.jpg"></image>
<view class="wrapper">
  <view class="curWeather">
    <view class="curTemperature">
      <view class="city">{{city}}  {{district}}</view>
      <view class="street">{{street}}</view>
      <view class="tmp">{{now.tmp}}°</view>
      <view class="type">{{now.cond.txt}} | 空气 {{quality.city.qlty}}</view>
    </view>
    <view class="curExtern">
      <view class="wind">
        <view class="">{{now.wind.dir}}</view>
        <view wx:if="{{now.wind.sc=='微风'}}" class="val">{{"<="}}2级</view>
        <view wx:else class="val">{{now.wind.sc}}级</view>
      </view>
      <view class="line"></view>
      <view class="relWet">
        <view class="">相对湿度</view>
        <view class="val">{{now.hum}}%</view>
      </view>
      <view class="line"></view>
      <view class="humanTmp">
        <view class="">体感温度</view>
        <view class="val">{{now.fl}}°</view>
      </view>
    </view>
  </view>
  <view class="forecast">
    <block wx:for="{{forecast}}" wx:for-index="index" wx:for-item="fc">
      <view class="castItem">
        <view class="castDay">{{showday[index]}}</view>
        <view class="castType">
          <image class="typeImg" src="../../icons/{{fc.cond.code_d}}.png"></image>
          {{fc.cond.txt_d}} | {{quality.city.qlty}}
        </view>
        <view class="castTmp">
          {{fc.tmp.max}}° / {{fc.tmp.min}}°
        </view>
      </view>
    </block>
  </view>
</view>

  index.wxss 文件的代码如下:

/**index.wxss**/
.wrapper{
  width:100%;
  height:100%;
  box-sizing: border-box;
  position:absolute;/*绝对定位*/
  top:0;
  left:0;
  padding:30rpx;
  font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}

.curWeather{
  height:650rpx;
  display: flex;
  flex-direction: column;/*纵向*/
}

.bg{
  height:700rpx; 
  width:750rpx;
}

.curTemperature{
  color:#fff;
  font-size: 0.8em;
  flex-grow: 1;/*表示将剩余的空间分配给它*/
}

.tmp{
  font-size: 5em;
}
.curExtern{
  display: flex;
  flex-direction: row;/*横向*/
  justify-content: space-around;
  color:#019CCA;
}
.val{
  text-align: center;
  font-size: 1.2em;
}
.line{
  border:0.9rpx solid #ff0;
}
.typeImg{
  width:50rpx;
  height:50rpx;
  vertical-align: middle;
}
.castItem{
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  border-bottom: 1rpx solid #0ff; 
  padding:50rpx 0;
}
.forecast{
  color:#019CCA;
  /*background: #aaa;*/
  margin-top:40rpx;
}


通过经纬度获取地理位置方法如下:







  微信发送请求的 API 接口代码如下所示:

 

wx.request({
  url: 'test.php', //仅为示例,并非真实的接口地址
  data: {  //参数
     x: '' ,
     y: ''
  },
  header: {
      'content-type': 'application/json'
  },
  success: function(res) { //请求成功后执行的回调函数,res为返回的数据。
    console.log(res.data)
  }
})

 index.js 代码如下:

//index.js
//获取应用实例
var app = getApp()
Page({
  data: {
     weekday:['周日','周一','周二','周三','周四','周五','周六'],
     showday:['今天','明天','']
  },
  //当页面加载完成
  onLoad: function () {
    var that = this;
    var date = new Date();
    console.log(date.getDay());
    that.setData({
      'showday[2]': this.data.weekday[(date.getDay() + 2)%7]
    });
    console.log(this.data.showday);
    wx.getLocation({
      success: function (res) {
        var latitude = res.latitude;//纬度
        var longitude = res.longitude;//经度
        console.log(latitude + "----" + longitude);
        that.getCity(latitude, longitude);//调用自己写的函数获得城市
      },
    })
  },
  //获得城市的函数定义
  getCity: function (lat, lng) {
    var url = "https://api.map.baidu.com/geocoder/v2/";
    var param = {
      location: lat + "," + lng,
      output: "json",//返回的数据格式
      ak: "MKABLw7PZssnQPy0BmnV2e6vcUyKWZxf"//地图api的ak
    };
    var that = this;
    //发出请求获取数据
    wx.request({
      url: url,
      data: param,
      success: function (res) {
        console.log(res);
        var city = res.data.result.addressComponent.city;
        var district = res.data.result.addressComponent.district;
        var street = res.data.result.addressComponent.street;
        that.setData({
          city: city,
          district: district,
          street: street
        });
        //调用自定义的函数获取天气信息
        city = city.substring(0, city.length - 1);//截掉最后一个字"市"
        that.getWeather(city);
      }
    })
  },
  //获取天气信息函数
  getWeather: function (city) {
    console.log(city);//注意传递的参数需是城市名或拼音等,详情见api文档,如果给的不是城市名,则无空气质量的值。城市名要去掉"市"字。
    var that = this;
    var url = "https://free-api.heweather.com/v5/weather";
    var param = {
      key: "4a555d4d1adc451d8ceeaa73869c9519",
      city: city
    };
    //发出请求
    wx.request({
      url: url,
      data: param,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res);
        that.setData({
          now: res.data.HeWeather5[0].now, /** 今天天气情况数组 /
          forecast: res.data.HeWeather5[0].daily_forecast, /** 预报天气情况数组 /
          quality:res.data.HeWeather5[0].aqi /** 空气质量 */
        });
      }
    })
  }
});

 数组访问方式查看微信小程序开发工具控制台输出数组查看:

 


 好了!到此为止就完成了!!


展开阅读全文

没有更多推荐了,返回首页