V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
min1214821
V2EX  ›  微信

用 uniapp 写个天气的微信小程序和支付宝小程序

  •  
  •   min1214821 · 2019-09-10 11:22:40 +08:00 · 2792 次点击
    这是一个创建于 1690 天前的主题,其中的信息可能已经有所发展或是发生改变。

    为什么是两个小程序,而不是多个平台的、因为注册头条小程序的没有资格就放弃了其他平台的了,为何做此小程序是因为最近刚好有空,用 uniapp 来练练手。

    经过最近两年多的发展,小程序的地位也逐渐越来越高了,各个平台前赴后继做了自家的小程序平台,随着市场的需求越来愈多,我们开发各平台的小程序的激情也随(被)之(逼)高(无)涨(奈)。

    为何选择 uniapp ? uni-app 是一个使用 Vue.js 开发所有前端应用的框架,开发者编写一套代码,可发布到 iOS、Android、H5、以及各种小程序(微信 /支付宝 /百度 /头条 /QQ/钉钉)等多个平台。即使不跨端,uni-app 同时也是更好的小程序开发框架。来自官方。喜欢 taro,wepy,mpvue 的朋友也莫喷我,大家各有所好,大家开心就好。

    智行天气小程序(支付宝小程序、微信小程序)

    效果图

    1、获取位置信息

    在定位功能中,本程序用到腾讯地图的 api 以及 腾讯天气的 api 接口,

    需要到官网中注册开发者账号,通过注册后得到的 appKey 来请求我们需要的数据,详细注册步骤请自行度娘

    由于需要用到定位功能,uniapp 的 getLocation 方法获取到的是当前位置的坐标,然后对应百度地图具体城市

    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
    			}
    		  }
    		});
    	}
    })
    
    
    

    2、查询天气

    得到城市名后,再用城市名查询天气的接口,得到未来几天的天气预报。 天气接口使用腾讯天气接口 api。 在小程序中使用前,要在小程序设置界面,开发设置中添加 request 合法域名。

    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
        }
    }
    

    3、小程序界面

    由于没有什么审美,缺乏想象力,参考腾讯天气的界面来做的。功能十分简单,查看当前地区的天气和切换其他地区的天气,查看最近 24 小时的天气情况以及最近 6 天的天气情况,展示今天的农历时间。

    4、插件使用

    想快速完成小程序的搭建,里面的折线图采用的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,

    城市选择组件

    <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. 后续将代码放到https://github.com/galan99
    2 条回复    2019-09-11 12:14:27 +08:00
    linxl
        1
    linxl  
       2019-09-10 11:24:50 +08:00
    最近再看小程序的文档, 简直头皮发麻...
    min1214821
        2
    min1214821  
    OP
       2019-09-11 12:14:27 +08:00
    使用的腾讯地图 api,文中百度地图文案出错,不好意思了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4834 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 05:38 · PVG 13:38 · LAX 22:38 · JFK 01:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.