微信小程序-天氣預報案例之和風天氣API

小程序-天氣預報,在現實生活中是非常常用的,我們平時都可以通過自己的手機上面或網上進行查看天氣等等;
這個demo可以應用到自己的小程序模塊上。
本案例先弄個簡約版本的v1.0.0…

前期準備:

  • 申請自己的微信小程序,雲開發環境也弄一下(用來模擬後端增刪查改數據);
  • 氣象數據:看完了百度天氣,數據太少了;最後使用的是和風天氣,需自行註冊賬號,獲取自己的 key;
  • 版本對比:免費版(數據少一些),建議申請開發者版(需個人去認證一下),商業版(功能更多)但要Q,博主木有Q;具體使用自行查閱文檔哈…

天氣來源:
我用的是開發版(項目用到接口有:實況天氣now,7天預報forecast,逐3小時預報hourly,生活指數lifestyle,城市搜索find,熱門城市top等等),相關參數看文檔哈…

授權-位置:
具體看一下微信小程序文檔

數據存儲:
具體看一下雲開發文檔

頁面大致如下,後續再進行優化升級;
天氣預報
天氣參數
我的城市
搜索-熱門城市
搜索-城市
部分代碼展示:

//授權用戶位置-先判斷
  autoUserLocation(){
    let that = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          console.log('位置未授權')
          that.globalData.is_Address = 0;
          wx.authorize({
            scope: 'scope.userLocation',
            success(res){
              that.getWxLocation();
            },
            fail(res){
              console.log('~~取消位置授權~~')
              wx.showModal({
                  title:'定位失敗',
                  content:'請允許”使用我的地理位置“後,再查看定位城市信息,默認爲您展示廣州的天氣信息。',
                  showCancel:false,
                  success(res) {
                    if (res.confirm) {
                      wx.openSetting({
                        success: (ret) => {
                          if(ret.authSetting['scope.userLocation']){
                            that.getWxLocation();
                          }else{
                            //返回-回調
                            if (that.isCancleCallback){
                              that.isCancleCallback(ret);
                             }
                          }
                         }
                      })
                   }
                }
              })
            }
          })
        }else{
          console.log('位置已授權')
          that.getWxLocation();
        }
      }
    })
  },

//獲取今日天氣
  getWeather(location){
    let that = this,
        key = globalData.key;
    const newWeatherRecord = that.data.weatherRecord,
          newWeaVal = that.data.weatherRecord.val;
    var params = {};
    params.location = location;
    params.key = key;
    that.setData({
      weatherParms:params
    })

    util.showLoading('加載中...')

    //***現在的***
    util.requestAjax.post(`${globalData.requestUrl.weather}`+'now',params)
     .then((res)=> {
      // console.log(res)
       const data = res.data.HeWeather6[0],
              dataNow = data.now;
        newWeaVal['pres'] = dataNow.pres;
        newWeaVal['hum'] = dataNow.hum;
        newWeaVal['wind_dir'] = dataNow.wind_dir;
        newWeaVal['wind_spd'] = dataNow.wind_spd;
        newWeaVal['fl'] = dataNow.fl;
        newWeaVal['vis'] = dataNow.vis;
        that.setData({
          nowWeather:dataNow,
          cityName: data.basic.location,
          weekday: util.formatWeekday(new Date()),
          weatherRecord: newWeatherRecord
        })
    }).catch((res)=>{
      console.log(res);
    });

     //
    Promise.all([that.getHourWeather(),that.getSevenWeather(),that.getLifeStyle()])
      .then((res) => {
      //  console.log(res)
      })
      .catch((err)=>{
      })
  },


 //獲取我的地址 從雲後臺
  getMyCityWeater(){
    let that = this;
    util.showLoading('加載中...');
    db.collection('cityWeather').where({
      _openid: that.data.openid
    }).get({
      async success(res){
        // console.log(res.data)
        var result = res.data;
        if(result.length <= 0){
          console.log('沒有自己');
        }else{
          var cityArr = result[0].cityArr;
          //異步回調 async一下
          let arr = [],newArr;
          for (let i = 0; i < cityArr.length; i++) {
            try {
              let val = await that.getWeather(cityArr[i]);
              // console.log(val)
              arr.push(val);
              //重整一下數組
              newArr = arr.map(((item, index)=> {
                return Object.assign(item,{city:cityArr[index],isTouchMove:false})
              }))
            } catch (e) {}
          }
          that.setData({
            myCityWeatherList: newArr
          })
        }
       
      },fail(res){
        console.log(res)
      }
    })
  },

這裏的app.js,自行到和風天氣官網申請key哦…
在這裏插入圖片描述
輸入你自己雲開發的圖片文件夾地址:(weather.js和city.js)
在這裏插入圖片描述

圖片文件夾地址如下圖:
在這裏插入圖片描述

  • 如上配置不懂的可留言或私信,謝謝~
  • 僅供學習參考,不作商業用途~

上架一下:
在這裏插入圖片描述
在這裏插入圖片描述
創作不易哈~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章