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

小程序端怎样实现持续定位功能

分类:uni小程序sdk

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

2020-04-26 13:35 负责人:无 分享
已邀请:
gweii

gweii

自己研究了一下,其实不用搞什么原生扩展,在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后提示用户,更好的做法是提示后切换到设置页,方便用户快速设置。

DCloud_Android_ST

DCloud_Android_ST

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

gweii

gweii

@DCloud_Android_ST 请问wx.onLocationChange这个api的支持情况有进展么?在华为手机上比较频繁调用uni.getLocation会失败:

  • 2***@qq.com

    应该无解,开发工具上是30秒内只返回一次正确其余都提示错误,真机时按不同机型时间不同,得换startLocationUpdateBackground中的onLocationChange方法

    2022-10-10 12:26

该问题目前已经被锁定, 无法添加新回复