微信小程序团队在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>