小程序自己api接口有对应的wx.onLocationChange(function callback),可以监听位置的改变,
uniapp中,怎么监听位置的改变呢,或者怎么样可以实现持续定位的功能呢

4***@qq.com
- 发布:2020-04-26 13:35
- 更新:2021-05-07 18:18
- 阅读:5054


自己研究了一下,其实不用搞什么原生扩展,在manifest.json中增加配置
"requiredBackgroundModes": [ "location" ]
然后在程序里直接调用api wx.startLocationUpdateBackground、wx.onLocationChange、wx.stopLocationUpdate
<script>
data() {
return {
watchingLocationChange: false
}
},
onShow() {
this.watchLocationChange();
},
onHide() {
this.unwatchLocationChange();
},
methods: {
onLocationChange(res) {
// 在这里响应位置变化
},
watchLocationChange() {
if (this.watchingLocationChange) return ;
wx.startLocationUpdateBackground({
success: (res) => {
wx.onLocationChange(this.onLocationChange);
this.watchingLocationChange = true;
},
fail: (res) => {
const msg = '开启后台定位失败。(' + JSON.stringify(res) + ')';
uni.showToast({
icon: 'none',
title: msg,
duration: 3000
});
console.log(msg);
}
});
},
unwatchLocationChange() {
if (!this.watchingLocationChange) return ;
wx.stopLocationUpdate({
success: () => {
this.watchingLocationChange = false;
console.log("已关闭后台定位");
},
fail: (res) => {
console.log("关闭后台定位失败。(" + JSON.stringify(res) + ")")
}
});
}
}
</script>
最后在启动小程序后进入设置页,把位置信息的权限改成“使用小程序期间和离开小程序后”就可以了。这一步也可以在wx.startLocationUpdateBackground执行fail后提示用户,更好的做法是提示后切换到设置页,方便用户快速设置。

uniapp暂时没有提供功能api。可以小程序宿主实现持续定位的原生扩展提供给小程序 调用实现该功能。https://nativesupport.dcloud.net.cn/UniMPDocs/Extension/android