用uniapp寫個天氣的微信小程序和支付寶小程序

爲何是兩個小程序,而不是多個平臺的、由於註冊頭條小程序的沒有資格就放棄了其餘平臺的了,爲什麼作此小程序是由於最近恰好有空,用uniapp來練練手。前端

通過最近兩年多的發展,小程序的地位也逐漸愈來愈高了,各個平臺前赴後繼作了自家的小程序平臺,隨着市場的需求越來愈多,咱們開發各平臺的小程序的激情也隨(被)之(逼)高(無)漲(奈)。vue

爲什麼選擇uniapp?uni-app 是一個使用 Vue.js 開發全部前端應用的框架,開發者編寫一套代碼,可發佈到iOS、Android、H五、以及各類小程序(微信/支付寶/百度/頭條/QQ/釘釘)等多個平臺。即便不跨端,uni-app同時也是更好的小程序開發框架。來自官方。喜歡taro, wepy,mpvue的朋友也莫噴我,你們各有所好,你們開心就好。git

智行天氣小程序(支付寶小程序、微信小程序)

效果圖

一、獲取位置信息

在定位功能中,本程序用到騰訊地圖的api 以及 騰訊天氣的api接口,github

須要到官網中註冊開發者帳號,經過註冊後獲得的appKey來請求咱們須要的數據,詳細註冊步驟請自行度娘ajax

因爲須要用到定位功能,uniapp的getLocation方法獲取到的是當前位置的座標,而後對應騰訊地圖具體城市npm

uni.getLocation({
	// #ifdef MP-WEIXIN
	type: 'wgs84',
	// #endif
	async success (res) {
		const {latitude, longitude} = res
		const result = await that.ajax({url: 'https://apis.map.qq.com/ws/geocoder/v1', data: {
			location: `${latitude},${longitude}`,
			key: ''
		}})
		let {province, city, district} = result.result.address_component
		that.getData(province, city, district)
	},
	fail(){
		uni.showModal({
		  content: '檢測到您沒打開定位權限,是否去設置打開?',
		  confirmText: "確認",
		  cancelText: "取消",
		  success: function (res) {
			if (res.confirm) {
			  // #ifdef MP-WEIXIN
			  wx.openSetting({
				success: (res) => {
					that.getIn()
				}
			  })
			  // #endif
			  // #ifdef MP-ALIPAY
			  my.openSetting({
				 success: (res) => {
					that.getIn()
				 }
			  })
			  // #endif
			}
		  }
		});
	}
})


複製代碼

二、查詢天氣

獲得城市名後,再用城市名查詢天氣的接口,獲得將來幾天的天氣預報。 天氣接口使用騰訊天氣接口api。 在小程序中使用前,要在小程序設置界面,開發設置中添加request合法域名。canvas

methods: {
    async getData(province, city, district){
        const that = this
        const data = await that.ajax({url: 'https://wis.qq.com/weather/common', data: {
        	source: 'xw',
        	weather_type: 'observe|alarm|air|forecast_1h|forecast_24h|index|limit|tips|rise',
        	province: province,
        	city: city,
        	county: district
        }})
        that.region = [province, city, district]
        if(data.status != 200){
        	uni.showToast({
        	    title: result.message,
        		icon: 'none'
        	});
        	return false;
        }
        if(!data.data.air.aqi_name){
        	uni.showToast({
        	    title: '暫無該地區的天氣信息',
        		icon: 'none'
        	});
        	return false;
        }
        that.data = data.data
    }
}
複製代碼

三、小程序界面

因爲沒有什麼審美,缺少想象力,參考騰訊天氣的界面來作的。功能十分簡單,查看當前地區的天氣和切換其餘地區的天氣,查看最近24小時的天氣狀況以及最近6天的天氣狀況,展現今天的農曆時間。小程序

四、插件使用

想快速完成小程序的搭建,裏面的折線圖採用的uchart.js, 由於能夠兼容支付寶小程序和微信小程序,農曆查詢也是採用的插件calendar.js

折線圖在支付寶小程序中會有模糊的問題,須要作兼容處理微信小程序

<template>
<!-- #ifdef MP-ALIPAY -->
<canvas canvas-id="canvas" id="canvas" width="750" height="240" style="width:750rpx;height:240rpx;" class="canvas">
</canvas>
<!-- #endif -->
<!-- #ifdef MP-WEIXIN -->
<canvas canvas-id="canvas" id="canvas" class="canvas">
</canvas>
<!-- #endif -->
</template>

<script>
var wxCharts = require('../../utils/chart.js');
lineChart = new wxCharts({
	$this: this,
	canvasId: 'canvas',
	type: 'line',
	categories: ['', '', '', '', '' ,''],
	colors: ['#ffad35', '#4fc3f7'],
	background: '#fff',
	animation: true,
	series: [{
		name: '',
		data: that.max,
		format: function (val, name) {
			return val + '°';
		}
	}, {
		name: '',
		data: that.min,
		format: function (val, name) {
			return val + '°';
		}
	}],
	xAxis: {
		disableGrid: true,
		disabled: true,
		axisLine: false
	},
	yAxis: {
		max: Math.max.apply(Math, that.max) * 1 + 0.1,
		disabled: true,
		disableGrid: true,
	},
	legend:{ 
		show: false 
	},
	// #ifdef MP-ALIPAY
	pixelRatio: that.pixelRatio, // 解決支付寶模糊問題
	// #endif
	width: that.cWidth,
	height: that.cHeight
});
</script>
複製代碼


陽曆插件使用
<script>
var time = require('../../utils/utils.js').calendar.solar2lunar();
let day = `${time.cMonth}月${time.cDay} ${time.ncWeek} 農曆${time.IMonthCn}${time.IDayCn}` // 9月10 星期二 陽曆八月十二
</script>
複製代碼

微信小程序有城市選擇組件,支付寶的沒有能夠直接使用的城市組件,uniapp官方介紹:支持安裝 mpvue 組件,但npm方式不支持小程序自定義組件(如 wxml格式的vant-weapp),找到一款支付寶能夠使用的城市插件:mpvue-citypicker,api

城市選擇組件

<template>
    <view class="txt-location" @tap="showCityPicker">
		<view class="icon"></view>
		<block v-if="region.length">{{region[0]}}{{region[1]}}{{region[2]}}</block>
		<block v-else>選擇城市</block>
		<!-- #ifdef MP-WEIXIN -->
		<picker class="city" mode="region" @change="handleChange" :value="region">
			<view class="picker">
				當前選擇:{{region[0]}},{{region[1]}},{{region[2]}}
			</view>
		 </picker>
		<!-- #endif -->
	</view>
    <mpvue-city-picker ref="mpvueCityPicker" :pickerValueDefault="pickerValueDefault" @onConfirm="onConfirm"></mpvue-city-picker>
</template>

<script>
import mpvueCityPicker from 'mpvue-citypicker';
export default {
  data() {
    return {
      region: [],
      pickerValueDefault: [0, 0, 1]
    };
  },
  components: {
    mpvueCityPicker
  },
  methods: {
    showCityPicker() {
        // #ifdef MP-ALIPAY
        this.$refs.mpvueCityPicker.show()
        // #endif
    },
    onConfirm(e) {
        if(e.label){
            this.region = e.label.split('-')
            this.getData(this.region[0], this.region[1], this.region[2])
        }
    },
    handleChange(e) {
        this.region = e.detail.value
	    this.getData(this.region[0], this.region[1], this.region[2])
    }
  }
};
</script>
複製代碼

總結

  1. 界面很快就搭建完成,提供了較爲完整的組件以及各類API2
  2. 天氣接口查詢的騰訊天氣的,須要作過濾處理才能使用,某些地區查詢天氣沒有返回須要友情提示處理
  3. 第一次作支付寶小程序遇到的坑很多,例如圖表模糊,城市選擇組件須要本身作,消息提示框uni.showToast使用時須要兼容,支付寶不能使用duration字段,獲取位置uni.getLocation使用時也須要兼容,支付寶不能使用type字段等。
  4. 程序的提交審覈比較快,個人大概是用了一天的時間就申請好了。可是支付寶審覈比較慢
  5. 後續將代碼放到github.com/galan99
相關文章
相關標籤/搜索