欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

微信小程序—天气预报

程序员文章站 2022-07-14 15:51:14
...

微信小程序—天气预报
作者:邱名涛
撰写时间:2020 年05 月06日
技术要点:百度天气api,查询天气,未来三天 天气预测。
微信小程序—天气预报
wxss.

/**index.wxss**/
page{
  height:100%;
}

.content {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  font-family: 微软雅黑,宋体;
  box-sizing: border-box;
  color: #FFFFFF;
  font-size: 17px;
  background-size:100% 100%;
  /* background-color: #F2F2F8 */
}


/*当日天气*/
.info {
  width: 100%;
  height: 160px;
}

/*城市和日期显示*/
.city {
  width: 100%;
  text-align: center;
  padding-top: 30rpx;
  padding-bottom: 30rpx;
}

/*周几*/
.city .weekday {
  float: left;
  font-size: 30rpx;
  font-weight: bold;
  text-align: left;
  padding-top: 20rpx;
  padding-left: 30rpx;
  width: 30%;
}

/*城市名称*/
.city .cityName {
  display:inline;
  font-size: 50rpx;
}

/*日期*/
.city .currentDate {
  float: right;
  font-size: 30rpx;
  font-weight: bold;
  text-align: right;
  padding-top: 20rpx;
  padding-right: 30rpx;
  width: 30%;
}

/*实时温度块*/
.temp {
  margin: 20rpx 20rpx 0 0;
  text-align: center;
  padding-bottom: 30rpx;
}

/*实时温度*/
.currentTemp {
  font-size: 120rpx;
  line-height: 130rpx;
  position: relative;
  display:inline-block;
  color: #FFFFFF;
}

/*实时温度右侧部分*/
.temp_right {
  position: relative;
  display: inline-block;
  padding-left: 10rpx;
  vertical-align: top;
  text-align: left;
}

/*摄氏度符号*/
.celsius {
  font-size: 40rpx;
  padding-top: 10rpx;
  color: #FFFFFF;
}

/*实时文字*/
.realtime {
  font-size: 30rpx;
  padding-top: 5rpx;
}

/**天气图标**/
.weatherIcon {
  margin: 0 auto;  
  display: flex;
  justify-content: center;
  overflow: hidden;
  width: 161rpx;
  height: 161rpx;
  border-radius: 50%;
}

/*类型*/
.type {
  font-weight: bold;
  text-align: center;
}

/*温度范围*/
.tempRange {
  font-weight: bold;
  margin-top: 20rpx;
  text-align: center;
  padding-top:5rpx;
}

/*风向风速*/
.wind {
  font-weight: bold;
  margin: 20rpx 0;
  text-align: center;
  padding-top:5rpx;
}

/*空气质量*/
.air {
  width: 35%;
  font-weight: bold;
  text-align: center;
  padding: 5rpx;
  margin: 0 auto;  
  display: flex;
  justify-content: center;
  border: 1px solid #00EE00;
  background-color: #00EE00;
  border-radius: 10rpx
}

/*最近3天天气*/
.forecast {
  width: 100%;
  display: flex;
  margin-top: 480rpx;
  align-self: flex-end;
  padding-bottom: 30rpx;
  font-weight: bold;
}

/*最近3天天气图标*/
.forecastIcon {
  margin: 0 auto;  
  display: flex;
  justify-content: center;
  overflow: hidden;
  width: 100rpx;
  height: 100rpx;
}

/*每一天的天气*/
.next-day {
  width: 30%;
  height: 430rpx;
  text-align: center;
  line-height: 30px;
  font-size: 16px;
  margin: 0 10rpx;
  border: 2px solid #043567;
  border-radius: 10rpx;
  box-shadow: 10px 10px 5px #888888;
}

/*日期*/
.date {
  margin-bottom: 20rpx;
  border-bottom: 1px solid #043567;
  color: #FFFFFF;
}

/*指数块*/
.tips {
  width: 90%;
  padding: 10rpx;
  margin: 30rpx auto;
  border-radius: 10rpx;
  border: 2px solid #043567;
  box-shadow: 10px 10px 5px #888888;
}

/*指数文字*/
.index {
  color: #FFFFFF;
  font-weight: bold;
  margin: 5px 0;
}

/*描述*/
.description {
  line-height: 22px;
  margin: 5px 0;
}

/*搜索区域*/
.search-area {
  display: flex;
  padding: 1rem 0.5rem;
}

/*输入框*/
.search-area input {
  width: 60%;
  height: 38px;
  line-height: 38px;
  
  border: 1px solid #CCC;
  box-shadow: 3px 3px 6px 0px #CCC;
  color: #000;
  background-color: #FFF;
  border-radius: 5px;
  margin: 0 auto;  
  display: flex;
  padding-left: 30rpx;
}

/*按钮*/
.search-area button {
  width: 20%;
  height: 40px;
  line-height: 40px;
  margin-left: 2rpx;
}

wxml.

<!--index.wxml-->
<view class="content">
  <scroll-view scroll-y='true' style='height:{{scroll_height}}rpx' enable-back-to-top='true' scroll-top='{{topNum}}'>
  <image class='background' src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1588698509085&di=ab467dbadbe355e4d8be2d4ea0ac012f&imgtype=0&src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F2018-09-03%2F5b8cc37540612.jpg" mode="aspectFill"></image>
  <!--当日天气-->
  <view class="info">
    <view class='city'>
      <view class='weekday'>{{weekday}}</view>
      <view class='cityName'>{{currentWeather.currentCity}}</view>
      <view class='currentDate'>{{currentDate}}</view>
    </view>
 
    <view class='temp'>
      <view class='currentTemp'>{{currentWeather.date}}</view>
      <view class = 'temp_right'>
        <view class='celsius'>℃</view>
        <view class='realtime'>(实时)</view>
      </view>
    </view>

    <image class='weatherIcon' src='{{iconURL}}' mode="Widthfix"></image>
    <view class='type'>{{currentWeather.weatherDesc}}</view>
    <view class='tempRange'>{{currentWeather.temperature}}</view>
    <view class='wind'>{{currentWeather.wind}}</view>
    <view class='air' style="background:{{airColor}}; border:{{airColor}}">{{currentWeather.pm25}}  {{airClass}}</view>
  </view>

  <!--最近3天天气-->
  <view class='forecast'>
    <view class='next-day' wx:for="{{forecast}}" wx:key="{{index}}" > 
      <view class='detail date'>{{item.date}}</view>
      <image class='forecastIcon' src='{{item.iconURL}}' mode="Widthfix"></image>
      <view class='detail'>{{item.weather}}</view>
      <view class='detail'>{{item.temperature}}</view>
      <view class='detail'>{{item.windDeriction}}</view>
      <view class='detail'>{{item.windSpeed}}</view>
    </view>
  </view>

  <!--感冒指数-->
  <view class='tips'>   
    <view class='index'>感冒指数:{{ganmao.zs}}</view>
    <view>
      <view class='description'>{{ganmao.des}}</view>
    </view>
  </view>

  <!--运动指数-->
  <view class='tips'>   
    <view class='index'>运动指数:{{yundong.zs}}</view>
    <view>
      <view class='description'>{{yundong.des}}</view>
    </view>
  </view>

  <!--紫外线指数-->
  <view class='tips'>   
    <view class='index'>紫外线指数:{{ziwaixian.zs}}</view>
    <view>
      <view class='description'>{{ziwaixian.des}}</view>
    </view>
  </view>

  <!--洗车指数-->
  <view class='tips'>   
    <view class='index'>洗车指数:{{xiche.zs}}</view>
    <view>
      <view class='description'>{{xiche.des}}</view>
    </view>
  </view>

   <!-- 搜索 -->
  <view class='search-area'>
    <input bindinput='inputing' placeholder='查询其它城市天气' value='{{inputCity}}'></input>
    <button type='primary' size='mini' bindtap='bindSearch'>查询</button>
  </view>
  </scroll-view>
</view>

JS.

//index.js
//获取应用实例
const app = getApp()
//调用百度地图天气API的js文件
var bmap = require('../../libs/bmap-wx.js');

Page({
  //“分享”功能
  onShareAppMessage: function () {
    let that = this;
    return {
      title: '分享',
      path: '/pages/index',
      success: (res) => {
        console.log(res.shareTickets[0])
        wx.getShareInfo({
          shareTicket: res.shareTickets[0],
          success: (res) => {
            that.setData({
              isShow: true
            })
            console.log(that.setData.isShow)
          },
          fail: function (res) { console.log(res) },
          complete: function (res) { console.log(res) }
        })
      },
      fail: function (res) {
        console.log(res)
      }
    }
  },

  data: {
    currentWeather: {},
    inputCity: "",
    topNum: 0,
    scroll_height: 0
  },

  onLoad: function () {
    let windowHeight = wx.getSystemInfoSync().windowHeight // 屏幕的高度
    let windowWidth = wx.getSystemInfoSync().windowWidth // 屏幕的宽度
    this.setData({
      scroll_height: windowHeight * 750 / windowWidth
    });
    this.getWeather("");
  },

  //查询天气
  getWeather: function (cityName) {
    //提示“加载中”
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true
    });

    var that = this;

    // 新建百度地图对象 
    var BMap = new bmap.BMapWX({ 
      ak: 'WGcD2wviqL3MiIqyNgI4xbTd4hKjRYZE'
    });

    //查询失败
    var fail = function (data) {
      //关闭加载提示框
      wx.hideLoading();

      var statusCode = data["statusCode"];
      //城市名称查询不到,弹窗提示
      if (statusCode == "No result available") {
        wx.showModal({
          title: '提示',
          content: '输入的城市名称有误,请重新输入',
          confirmText: '好的',
          confirmColor: '#ACB4E3',
          showCancel: false,
        });
      }
    };

    //查询成功
    var success = function (data) {
      //关闭加载提示框
      wx.hideLoading();

      //获取当前的日期和星期几
      var currentDate = that.getDate().substring(5);
      var weekday = data.currentWeather[0].date.substring(0, 2);
      //currentDate = currentDate + "  " + weekday;

      //返回的数据包括2部分:data.currentWeather和data.originalData.results
      //console.log(data);
      //console.log(data.currentWeather);
      //console.log(data.originalData);
      //console.log(data.originalData.results);

      //第1部分数据示例
      var currentWeather = data.currentWeather[0];
      //currentWeather.currentCity:"济南市"
      //currentWeather.date:"周四 01月17日 (实时:3℃)"
      //currentWeather.pm25:"85"
      //currentWeather.temperature:"7 ~ -2℃"
      //currentWeather.weatherDesc:"晴"
      //currentWeather.wind:"南风微风"

      //获得天气图标URL
      var iconURL = that.getIconURL(currentWeather.weatherDesc);

      //截取出实时温度数据
      var begin = currentWeather.date.indexOf("时");
      var end = currentWeather.date.indexOf(")");
      currentWeather.date = currentWeather.date.substring(begin + 2, end - 1);
      //console.log(currentWeather.date);

      //调整温度范围显示
      currentWeather.temperature = that.tempSwitch(currentWeather.temperature);

      //判断空气质量等级
      var pm25 = currentWeather.pm25;
      var airClass = "";
      var airColor = "";
      if (pm25 <= 50) {
        airClass = "优";
        airColor = "#00EE00";
      }
      else if (pm25 > 50 && pm25 <= 100) {
        airClass = "良";
        airColor = "#EEEE00";
      }
      else if (pm25 > 100 && pm25 <= 150) {
        airClass = "轻度污染";
        airColor = "#FF8C00";
      }
      else if (pm25 > 150 && pm25 <= 200) {
        airClass = "中度污染";
        airColor = "#FF3030";
      }
      else if (pm25 > 200 && pm25 <= 300) {
        airClass = "重度污染";
        airColor = "#E066FF";
      }
      else {
        airClass = "严重污染";
        airColor = "#8B0000";
      }

      //第2部分数据示例
      var tipsArray = new Array(5);
      tipsArray = data.originalData.results[0].index;
      var chuanyi = tipsArray[0];
      var xiche = tipsArray[1];
      var ganmao = tipsArray[2];
      var yundong = tipsArray[3];
      var ziwaixian = tipsArray[4];

      //chuanyi.tipt:穿衣指数
      //chuanyi.zs:较冷
      //chuanyi.des:"建议着厚外套加毛衣等服装。年老体弱者宜着大衣、呢外套加羊毛衫。"

      //xiche.tipt:洗车指数
      //xiche.zs:较适宜
      //xiche.des:"较适宜洗车,未来一天无雨,风力较小,擦洗一新的汽车至少能保持一天。"

      //ganmao.tipt:感冒指数
      //ganmao.zs:少发
      //ganmao.des:"各项气象条件适宜,无明显降温过程,发生感冒机率较低。"

      //yundong.tipt:运动指数
      //yundong.zs:较适宜
      //yundong.des:"天气较好,无雨水困扰,较适宜进行各种运动,但因气温较低,在户外运动请注意增减衣物。"

      //ziwaixian.tipt:紫外线强度指数
      //ziwaixian.zs:中等
      //ziwaixian.des:"属中等强度紫外线辐射天气,外出时建议涂擦SPF高于15、PA+的防晒护肤品,戴帽子、太阳镜。"

      //未来3天的天气预报
      var forecastArray = new Array(4);
      forecastArray = data.originalData.results[0].weather_data;

      var forecast = new Array(3);
      for (var i = 0; i < 3; i++) {
        forecast[i] = forecastArray[i + 1];
        //调整日期显示
        forecast[i].date = that.getForecatDate(i, forecast[i].date);
        //获得天气图标URL
        forecast[i].iconURL = that.getIconURL(forecast[i].weather);
        //调整温度范围显示
        forecast[i].temperature = that.tempSwitch(forecast[i].temperature);
        //调整风向和风速显示,如果没有风速,则风速为空
        forecast[i].windDeriction = that.getWindDeriction(forecast[i].wind);
        forecast[i].windSpeed = that.getWindSpeed(forecast[i].wind);
      }

      //配置数据
      that.setData({
        iconURL: iconURL,
        currentWeather: currentWeather,
        currentDate: currentDate,
        weekday: weekday,
        airClass: airClass,
        airColor: airColor,
        forecast: forecast,
        ganmao: ganmao,
        yundong: yundong,
        ziwaixian: ziwaixian,
        xiche: xiche
      });
    }

    // 发起weather请求
    //cityName为空,查询定位城市天气
    if (!cityName) {
      BMap.weather({
        cityName: "",
        fail: fail,
        success: success
      });
    }
    //cityName不为空,查询输入城市天气
    else {
      BMap.weather({
        cityName: cityName,
        fail: fail,
        success: success
      });
    }
  },

  //日期显示
  getDate: function () {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    var currentdate = year + "年" + month + "月" + strDate + "日";
    return currentdate;
  },

  //未来3天预报中调整日期显示
  getForecatDate: function (index, weekday) {
    var date = this.getNextDate(index + 1);
    var result;
    result = date + " " + weekday;
    return result;
  },

  getNextDate: function (index) {
    var today = new Date();
    //后index天的日期
    var nextDate = new Date(today.getTime() + 24 * 60 * 60 * 1000 * index);
    var month = nextDate.getMonth() + 1;
    var strDate = nextDate.getDate();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    var result = month + "月" + strDate + "日";
    return result;
  },

  //转换温度范围显示格式,eg:"7 ~ -2℃"
  tempSwitch: function (temp) {
    var low;
    var high;
    var result;
    var flag = temp.indexOf("~");
    var length = temp.length;

    low = temp.substring(flag + 2, length - 1);
    high = temp.substring(0, flag - 1);
    result = low + " ~ " + high + "℃";

    return result;
  },

  //天气图标路径
  getIconURL: function (weatherDesc) {
    var condition = String(weatherDesc);
    var url = "";
    if (condition.includes("转")) {
      condition = condition.substring(0, condition.indexOf("转"));
    }

    if (condition.includes("晴")) {
      url = "https://ae01.alicdn.com/kf/Ue795d165d18d411f806163653eba07e2E.png";
    }
    else if (condition.includes("多云")) {
      url = "https://ae01.alicdn.com/kf/U8a2ae9f027804ababbd968d903f4b848I.png";
    }
    else if (condition.includes("阴")) {
      url = "https://ae01.alicdn.com/kf/U22db7f19a8ab432aa306922cbdca8c3ad.png";
    }
    else if (condition.includes("阵雨")) {
      url = "https://ae01.alicdn.com/kf/Ufc5cd30268754c1ab992632c4d4154a6N.png";
    }
    else if (condition.includes("雷阵雨")) {
      url = "https://ae01.alicdn.com/kf/U609378294db842a8bab0718dbfb9fc55n.png";
    }
    else if (condition.includes("雨夹雪")) {
      url = "https://ae01.alicdn.com/kf/Ub6893c94b53e49a1bc244c288f961c31T.png";
    }
    else if (condition.includes("小雨")) {
      url = "https://ae01.alicdn.com/kf/U02f202d1e9b4440589ae6b8ac0d93c58m.png";
    }
    else if (condition.includes("中雨")) {
      url = "https://ae01.alicdn.com/kf/Ubdca1610fa18458b971d9f25d42f4c79y.png";
    }
    else if (condition.includes("大雨")) {
      url = "https://ae01.alicdn.com/kf/U59e4bcdbb7144a56a3a60c0de7aeefb5D.png";
    }
    else if (condition.includes("暴雨")) {
      url = "https://ae01.alicdn.com/kf/U414646a0ee534868bb8e625d74acfbabg.png";
    }
    else if (condition.includes("阵雪")) {
      url = "https://ae01.alicdn.com/kf/U839ec136d5fa4b6ba6411d0806a06b3ce.png";
    }
    else if (condition.includes("小雪")) {
      url = "https://ae01.alicdn.com/kf/U3a4be42c858c4cc8aecde2b29425edf6A.png";
    }
    else if (condition.includes("中雪")) {
      url = "https://ae01.alicdn.com/kf/U46ab44e2a403469cb500f2514a9258c71.png";
    }
    else if (condition.includes("大雪")) {
      url = "https://ae01.alicdn.com/kf/U16a2a60ff3e04bc0b382c3f62491320bg.png";
    }
    else if (condition.includes("暴雪")) {
      url = "https://ae01.alicdn.com/kf/Ua7bca2b9687847f5952e0cd85f49a33fK.png";
    }
    else if (condition.includes("雾")) {
      url = "https://ae01.alicdn.com/kf/U0a6e366ca3bb442384d18327608a595dU.png";
    }
    else if (condition.includes("霾")) {
      url = "https://ae01.alicdn.com/kf/Uf5f07c706b2c43f5be20935a5f558df6A.png";
    }
    else if (condition.includes("沙尘暴")) {
      url = "https://ae01.alicdn.com/kf/U2878e9e827064379b924138cee998936z.png";
    }
    else {
      url = "https://ae01.alicdn.com/kf/U1cd176c4255041cea210642d754ca506C.png";
    }
    return url;
  },

  //获得风向
  getWindDeriction: function (wind) {
    var result = "";
    var index = this.seperateWind(wind);
    //信息中不包含风速,风向为全部信息
    if (index == -1) {
      result = wind;
    }
    //信息中包含风速,截取出风向
    else {
      result = wind.substring(0, index);
    }
    return result;
  },

  //获得风速
  getWindSpeed: function (wind) {
    var result = "";
    var index = this.seperateWind(wind);
    //信息中不包含风速,风速为空
    if (index == -1) {
      result = "";
    }
    //信息中包含风速,截取出风速
    else {
      result = wind.substring(index, wind.length);
    }
    return result;
  },

  //将风向和风力分开,获得分隔的索引值
  seperateWind: function (wind) {
    var numPattern = /[0-9]/;
    var result = "";
    if (numPattern.test(wind)) {
      //风力信息中包含数字
      var pattern = new RegExp("[0-9]+");
      var res = wind.match(pattern);
      result = res.index;
    }
    else if (wind.search("微风")) {
      var res = wind.match("微风");
      result = res.index;
    }
    else {
      //风力信息中不包含数字
      result = -1;
    }
    return result;
  },

  //获得输入框中的文字
  inputing: function (e) {
    // console.log(e);
    this.setData({ inputCity: e.detail.value });
  },

  //查询按钮
  bindSearch: function () {
    if (this.data.inputCity == '') {
      wx.showModal({
        title: '提示',
        content: '请先输入要查询的城市名称',
        confirmText: '好的',
        confirmColor: '#ACB4E3',
        showCancel: false,
      });
    }
    else {
      //查询天气
      this.getWeather(this.data.inputCity);

      // 一键回到顶部
      this.setData({
        topNum: 0
      });
    }
  }
})

相关标签: 微信小程序

上一篇: vim python

下一篇: msm8953背光