微信小程序開發實戰-天氣小程序

園齡6年8個月了,還一篇文章都沒寫過,慚愧!css

最近週末作了個天氣預報小程序,在這裏整理一下開發過程和注意點,給對小程序開發感興趣的夥伴們提供點參考。html

廢話很少說,先上圖最終效果:前端

 

下面進入正文:git

 

第一步  準備

0. 把微信小程序開發文檔過一遍。https://developers.weixin.qq.com/miniprogram/dev/framework/  做爲程序員,就要從0開始計數。程序員

1. 下載安裝微信開發者工具(https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html),這個就很少說了。web

2. 設計產品原型,咱們要把產品作成什麼樣。數據庫

先曬一下初版的原型,比較醜,見諒。(初版醜和簡陋先忍,後面能夠迭代)json

下面的代碼也會是初版,功能沒有上面掃碼看到的那麼多。我是但願能從0開始寫起,而後把每次迭代也寫上,讓你們能看到一個項目是怎麼從初版最簡陋的功能,逐步功能豐富和完善。這纔是一個項目真正的開發過程。一開始就作的很複雜很完備的,每每容易難產。小程序

 

 而後咱們接口須要向頁面提供的信息就明確了:位置名、實時溫度、天氣文字、空氣文字、今日日期、今日天氣情況。後端

 

第二步 啓程 開發小程序前端頁面

【10點20了,終於下班到家,有時間繼續補充了】

0.新建項目

打開微信開發者工具,建立一個新項目。暫起名「miniweather」(名字不重要,之後能夠隨時改)。以下圖:

 

建立完成後,默認微信開發者工具就把項目編譯預覽出來了,效果以下。

 

點擊「獲取頭像暱稱按鈕」,界面變成以下:

 

(請忽略我吊炸天的微信名)

 

1. 編寫頁面內容

因爲我們這個天氣預報只有一個頁面,就直接在index這個頁面改起,不必建立新頁面了。

刪掉index.wxml中的所有代碼,稍後重寫。

刪掉index.wxss中的所有樣式代碼,稍後重寫。

我們從頭寫起。若是你熟悉html和css,那麼這個wxml和wxss就很容易上手了。

先貼代碼以下

index.wxml:

 1 <view class="weather-wrapper">
 2   <view class="location-text">北京</view>
 3   <view class="temp">30°</view>
 4   <view class="weather">
 5     <text class="weather_txt"></text>
 6     <text class="air_label">空氣優</text>
 7   </view>
 8   <view class="day-weather">
 9     <view class="day-text">2019-09-12</view>
10     <view class="temp-text">晴轉多雲</view>
11   </view>
12 </view>

 

上面wxml( 至關於web開發的html )就這麼12行。把頁面須要的元素列出來,並加了對應的class名,稍後咱們能夠針對class設置樣式。

如今的效果是這樣的:

頁面沒有任何樣式,可是基本內容都有了。

接下來,編輯index.wxss文件(wxss至關於web開發的css),把樣式加上。

仍然是先貼代碼:

index.wxss

 1 .weather-wrapper{
 2   position: relative;
 3   padding-top: 20rpx;
 4   padding-bottom: 250rpx;
 5 }
 6 .location-text{
 7   text-align: center;
 8 }
 9 .temp {
10   text-align:center;
11   font-size:200rpx;
12   line-height:280rpx;
13   opacity:0.8;
14 }
15 .weather {
16   text-align: center;
17   font-size: 40rpx;
18   line-height: 56rpx;
19   opacity: 0.65;
20 }
21 .air_label{
22   margin-left: 20rpx;
23   border-radius: 10rpx;
24   padding:8rpx;
25 }
26 .day-weather {
27   display: flex;
28   align-items: center;
29   position: absolute;
30   bottom:0;
31   left: 40rpx;
32   right: 40rpx;
33   height: 90rpx;
34   font-size: 30rpx;
35   line-height: 42rpx;
36   color: rgba(0, 0, 0, 0.5)
37 }
38 .temp-text {
39   flex-grow: 1;
40   padding-right: 30rpx;
41   text-align: right;
42 }

 保存index.wxss文件,工具自動編譯,這下再看預覽效果,順眼多了

 

 

 

2. 加背景圖

頁面框架有了,可是尚未圖片資源,顯得很簡陋,這一步咱們給它加一個背景圖。

首先建立一個images/background目錄,而後把背景圖片存到backgrond目錄中。

以後,修改index.wxml文件,在weather-wrapper類中加入圖片:

<image src="/images/background/sunny.png" mode="scaleToFill" class="bgimg"></image>

mode="scaleToFill"表示將圖片拉伸填滿,能夠查看圖片的官方文檔瞭解詳情。

class="bgimg"  是咱們給圖片定義一個叫bgimg的類,方便稍後咱們給它設置樣式。

以後咱們的index.wxml變成以下:

<view class="weather-wrapper">
  <image src="/images/background/sunny.png" mode="scaleToFill" class="bgimg"></image>
  <view class="location-text">北京</view>
  <view class="temp">30°</view>
  <view class="weather">
    <text class="weather_txt"></text>
    <text class="air_label">空氣優</text>
  </view>
  <view class="day-weather">
    <view class="day-text">2019-09-12</view>
    <view class="temp-text">晴轉多雲</view>
  </view>
</view>

再編輯index.wxss,給bgimg設置樣式。添加代碼以下:

.bgimg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}

 

以後,咱們的index.wxss變成以下:

.weather-wrapper {
  position: relative;
  padding-top: 20rpx;
  padding-bottom: 350rpx;
}
.bgimg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}
.location-text {
  margin-top: 50rpx;
  text-align: center;
}
.temp {
  text-align: center;
  font-size: 200rpx;
  line-height: 280rpx;
  opacity: 0.8;
}
.weather {
  text-align: center;
  font-size: 40rpx;
  line-height: 56rpx;
  opacity: 0.65;
}
.air_label {
  margin-left: 20rpx;
  border-radius: 10rpx;
  padding: 8rpx;
}
.day-weather {
  display: flex;
  align-items: center;
  position: absolute;
  bottom: 0;
  left: 40rpx;
  right: 40rpx;
  height: 90rpx;
  font-size: 30rpx;
  line-height: 42rpx;
  color: rgba(0, 0, 0, 0.5);
}
.temp-text {
  flex-grow: 1;
  padding-right: 30rpx;
  text-align: right;
}

 

 

保存文件,點擊「編譯」按鈕,查看效果

 

 有了背景圖,看起來美觀多了。

【下方的白色空白是特地預留的,之後展現將來天氣的預報信息,這部分此篇文章篇幅所限就不寫了】

 

第三步  找數據源 提供數據接口

這一步可走的路就多了。

有專門提供天氣api接口的廠商,免費、收費都有。好比墨跡、彩雲、和風等專門就是幹這個的

也能夠本身寫代碼去爬數據。

這裏爲了學習,能夠先用和風天氣的免費接口,去上面註冊一個帳號,而後看官方文檔,瞭解怎麼獲取到天氣信息。

 

其實正規項目,咱們應該有本身的後端服務,後端本身製造、存儲數據或者和第三方(如和風天氣)交互獲取數據,本身的小程序只向本身的後端接口請求數據。不過這東西攤開來說就太多了,它是一整個技術棧,涉及了太多方面。

我是構建了本身的後端服務,可是對於初學者,我無法在這裏指導大家從頭開始構建。(想一想須要買雲主機、買域名、域名備案、進行環境配置、寫後端服務代碼、代碼上線部署等,一大攤子事,不是三言兩語或者幾篇文章能寫清楚的)

至於小程序力推的雲開發,我我的其實不推薦。雲開發雖然方便了開發者,省去買服務器、域名、數據庫等各類事,看似對開發者友好,但事情都有兩面性。雲開發塑造了一個封閉的生態圈,全部東西都在微信的統轄內,不利於互聯網的開放,若是想把數據給網站、app使用也很難。並且當用戶量大的時候,雲開發並不會節省多少成本。

 

因此接下來就讓小程序直接調用和風天氣的接口來獲取數據做爲演示。

第四步 小程序經過接口調數據,展現信息

0.移除無用代碼

對於數據的的操做,咱們在index.js中進行。默認的index.js中太多無用的東西了,天氣小程序不須要獲取用戶信息,因此不想關的都刪掉,最終index.js內容以下:

Page({
  data: {
  },
  onLoad: function () {
  }
})

1.設置頁面從js中獲取初始數據

其中data是用來存放頁面初始數據的,咱們能夠在裏面設置初始數據,傳遞給頁面。

修改後index.js內容以下:

Page({
  data: {
    location_text:'北京',
    temperature:'30°',
    now_weather: '晴',
    now_air: '優',
    today:'2019-09-12',
    today_weather: '晴轉多雲'
  },
  onLoad: function () {
  }
})

 而後修改index.wxml,接收這些參數,修改完的index.wxml以下:

<view class="weather-wrapper">
  <image src="/images/background/sunny.png" mode="scaleToFill" class="bgimg"></image>
  <view class="location-text">{{location_text}}</view>
  <view class="temp">{{temperature}}</view>
  <view class="weather">
    <text class="weather_txt">{{now_weather}}</text>
    <text class="air_label">空氣{{now_air}}</text>
  </view>
  <view class="day-weather">
    <view class="day-text">{{today}}</view>
    <view class="temp-text">{{today_weather}}</view>
  </view>
</view>

保存文件,自動編譯,查看效果:

 

 

2. js獲取和風天氣數據,渲染到頁面

 前置工做:

登陸和風天氣控制檯,建立應用,生成了一個免費版的key來使用。後面調用天氣接口須要用到這個key

 

獲取位置信息

要查詢當地天氣,須要先有位置數據,這個推薦使用騰訊位置服務。官方文檔寫的清清楚楚,直接用官方例子就行。

這個在小程序後臺開通,也要獲取一個key。

 

 

獲取位置信息須要用戶受權,須要把要獲取的受權信息寫在app.json中。 

app.json增長以下代碼:

"permission": {
    "scope.userLocation": {
      "desc": "你的位置信息將用於小程序獲取當前位置天氣"
    }
  },

 

利用位置信息,調用和風天氣接口獲取天氣數據

請求網絡接口用 wx.request()方法   文檔

把數據渲染到頁面

使用setData({})方法,把初始值換成咱們從接口獲取到的真實值。

 

最終index.js內容以下:

const QQMapWX = require('../../utils/qqmap-wx-jssdk.js')
Page({
  data: {
    location_text: '北京',
    temperature: '30°',
    now_weather: '晴',
    now_air: '優',
    today: '2019-09-12',
    today_weather: '晴轉多雲'
  },
  onLoad: function () {
    this.qqmapsdk = new QQMapWX({
      key: 'EAXBZ-33R3X-AA64F-7FIPQ-BY27J-5UF5B'
    })
    this.getCityAndWeather()
  },
  // 獲取位置及天氣
  getCityAndWeather() {
    var that = this;
    wx.getLocation({
      success: res => {
        this.location_pin = res.longitude + ',' + res.latitude
        this.qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: res2 => {
            let city = res2.result.address_component.city
            that.setData({
              location_text: city,
            })
            that.getNowWeather()
          }
        })
      },
      fail: () => {
        console.log('未受權位置');
      }
    })
  },

  // 獲取當前天氣
  getNowWeather() {
    let that = this
    let hfkey = '3b820c451ee144629f959b464b2dd6a5'
    let url = 'https://free-api.heweather.net/s6/weather/now?key=' + hfkey + '&location=' + this.location_pin

    wx.request({
      url: url,
      success: function (res) {
        console.log('success')
        console.log(res)
        let nowData = res.data.HeWeather6[0].now;
        //溫度數據
        let temperature = nowData.tmp
        //當前天氣文字描述
        let now_weather = nowData.cond_txt
        // 今日日期
        var date = new Date()
        const year = date.getFullYear()
        const month = date.getMonth() + 1
        const day = date.getDate()
        that.setData({
          temperature: temperature + '°',
          now_weather: now_weather,
          today: year + '-' + month + '-' + day
        })
      },
      fail: function (res) {
        console.log()
      }
    })
  }
})

 

上面只調用了一個接口獲取數據,要獲取頁面其它數據,還須要調用其它接口,方法大同小異,我這裏就不重複寫了。能夠參考上面的代碼自行實現。

 

可能遇到的問題及解決辦法:

1.提示域名不合法:能夠取消對域名的校驗(開發工具中 詳情->本地設置->勾選不校驗合法域名...),或者在公衆平臺小程序後臺把域名信息加進去。

 

本文完整代碼下載

完整代碼包: 下載地址

相關文章
相關標籤/搜索