1. 程式人生 > >小程式如何獲取當前的天氣預報

小程式如何獲取當前的天氣預報

大家好,我是陳楠酒肆,今天我為大家分享的是小程式獲取當前的天氣預報,我們先看看效果圖

在實現這個效果之前我們需要引用一個JS檔案,就是amap-wx.js,這個檔案可以在我的交流群裡下載。由於這裡我使用了高德地圖金鑰,因此,大家還需要在高德網站上註冊一個賬號,並獲取相應的金鑰,有關這點,我會單獨拉出來將,在此只做拋磚引玉。

好了,下面進入正題,假設大家有了高德地圖的金鑰,那麼下面我們該如何實現呢。

JS檔案如下:

const amapFile = require('../../utils/amap-wx.js'); //引用amap-wx.js檔案
const app = getApp();

Page({

  /**
   * 頁面的初始資料
   */
  data: {
    weather: [], //天氣物件
    markersData: {
      latitude: '',//緯度
      longitude: '',//經度
      key: "你的金鑰"//申請的高德地圖key
    },
 city:'',
    address:'',
    address2:'', 
  },

  /**
   * 生命週期函式--監聽頁面載入
   */
  onLoad: function (options) {
    that.loadInfo(); //執行函式
  },

  //獲取當前位置的經緯度
  loadInfo: function () {
    var that = this;
    wx.getLocation({
      type: 'gcj02', //返回可以用於wx.openLocation的經緯度
      success: function (res) {
        var latitude = res.latitude//維度
        var longitude = res.longitude//經度
        that.loadCity(latitude, longitude);
      }
    })
  },
  //把當前位置的經緯度傳給高德地圖,呼叫高德API獲取當前地理位置,天氣情況等資訊
  loadCity: function (latitude, longitude) {
    var that = this;
    var myAmapFun = new amapFile.AMapWX({ key: that.data.markersData.key });
    myAmapFun.getRegeo({
      location: '' + longitude + ',' + latitude + '',//location的格式為'經度,緯度'
      success: function (data) {
        console.log("開始資料");
        console.log(data[0]['regeocodeData']['addressComponent']['city']);
        that.setData({
          city: data[0]['regeocodeData']['addressComponent']['city'],
          address:data[0]['desc'],
          address2: data[0]['name']
        });
        console.log(data);
      },
      fail: function (info) { }
    });

    myAmapFun.getWeather({
      success: function (data) {
        that.setData({
          weather: data
        })
        console.log("開始資料2");
        console.log(data);
        //成功回撥
      },
      fail: function (info) {
        //失敗回撥
        console.log("開始資料3");
        console.log(info)
      }
    })
  },
  /**
   * 生命週期函式--監聽頁面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命週期函式--監聽頁面顯示
   */
  onShow: function () {
    
  },

  /**
   * 生命週期函式--監聽頁面隱藏
   */
  onHide: function () {
    
  },

  /**
   * 生命週期函式--監聽頁面解除安裝
   */
  onUnload: function () {
    
  },

  /**
   * 頁面相關事件處理函式--監聽使用者下拉動作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 頁面上拉觸底事件的處理函式
   */
  onReachBottom: function () {
    
  },

  /**
   * 使用者點選右上角分享
   */
  onShareAppMessage: function () {
    
  }
})

wxml檔案如下:

<view>所屬城市:{{weather.city.data}}</view>
<view>城市溼度:{{weather.humidity.data}}</view>
<view>城市溫度:{{weather.temperature.data}}</view>
<view>城市天氣:{{weather.weather.data}}</view>
<view>城市風向:{{weather.winddirection.data}}</view>
<view>城市風力:{{weather.windpower.data}}</view>

以上就是核心內容,小程式執行起來的效果是:

大家有需要的可以加入我的群號進行下載