微信小程序后台持续定位功能使用详解

微信小程序团队在7月30日更新了 基础库 2.8.0
其中新添加了小程序后台持续定位功能和联系定位的接口
从上到下分别是

1.wx.onLocationChange//监听位置实时变化

2.wx.stopLocationUpdate//关闭监听实时位置变化,前后台都停止消息接收

3.wx.startLocationUpdate//开启小程序进入前台时接收位置消息

4.wx.startLocationUpdataBackground//开启小程序进入前后台时均接收位置消息

详细信息可查看查看

<template>
	<div>
		<u-navbar :is-back="true" back-text="返回" back-icon-color='#b0d0fc' :back-text-style="{color: '#b0d0fc'}"
			:background="{
		             backgroundColor: '#fff',
					backgroundSize: 'cover',
					backgroundImage: 'linear-gradient(45deg, #567cf6, #56abfb)'
				}">
		</u-navbar>

		<u-button @click="start"> 开始定位</u-button>
		<u-button @click="end"> 结束定位</u-button>
		<u-button @click="toSetting"> 设置权限</u-button>

	</div>
</template>

<script>
	import moment from "moment"; // 格式化时间 插件	

	export default {
		data() {
			return {
				num: 0,
				list: [],
				res: null
			}
		},
		onLoad() {
			this.startBack() // 开启监控环境
		},
		methods: {
			
			//这个函数是一开始点击事件触发的:
			startBack() {
				let that = this;
				let index = 0

				let _locationChangeFn = (res) => {
					console.log('location change', res)

					let ss = moment().format('YYYY-MM-DD HH:mm:ss');
					console.log(ss)

					index += 2
					// 10秒上传1次经纬度
					if (index % 10 == 0) {
						// 执行自己的代码
						// that.saveLocation(res.longitude, res.latitude)
						console.log("执行上传点阵", index)
					}

					if (index > 1000) {
						index = 0
					}
				}
				wx.onLocationChange(_locationChangeFn);
			},

			start() {
				let _this = this;
				wx.startLocationUpdateBackground({
					success: (res) => {
						console.log(res + "开始了");
						// wx.onLocationChange(_locationChangeFn);
					},
					fail: (err) => {
						console.log('获取当前位置失败', err)
						_this.toSetting()
						
					}
				})
			},

			toSetting() {
				console.log("执行了设置方法")
				let self = this
				wx.openSetting({
					success(res) {
						console.log(res)
						if (res.authSetting["scope.userLocation"]) {
							// res.authSetting["scope.userLocation"]为trueb表示用户已同意获得定位信息,此时调用getlocation可以拿到信息
							// self.authorization() // 调用开始方法
						}
					},
					fail(err){
						console.log("open失败",err)
					}
				})
			},

			end() {

				wx.stopLocationUpdate({
					success: (res) => {
						console.log('stopLocationUpdate', res)
					}
				})

			}
		}
	}
</script>

<style lang="scss">

</style>

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值