wx.startLocationUpdateBackground和wx.onLocationChange的结合使用

项目使用uniapp 开发微信小程序,功能要求使用实时监听地理位置,可以使用官方api(wx.onLocationChange(function callback))需要结合(wx.startLocationUpdateBackground)使用

canIUse(){
	uni.getSetting({
		success: (res)=>{
			console.log('###### getSetting ######', res)
			if(res.authSetting['scope.userLocationBackground']) {
				this.getData()
			} else {
				this.getAuthorize()
			}
		}
	})
},
getData(){
	if(wx.startLocationUpdateBackground){
		wx.startLocationUpdateBackground({
			success: (res) => {
				if (wx.onLocationChange) {
					wx.onLocationChange((res1)=>{
						console.log('onLocationChange >>>>>>>>>>>>', res1)
						this.longitude = res1.longitude
						this.latitude = res1.latitude
						this.getPolyline({longitude: this.longitude, latitude: this.latitude})
					})
				} else {
					this.errHandle()
				}
				
			},
			fail: (err) => {
				this.openSetting()
				this.errHandle(err)
			}
		})
	} else {
		this.errHandle()
	}
},
getAuthorize(){
	console.log('getAuthorize======')
	uni.authorize({
		scope: 'scope.userLocationBackground',
		success: (res)=>{
			this.getData()
		},
		fail: (err)=>{
			console.log('getAuthorize fail------',err)
			this.openSetting()
		}
	})
},
openSetting(){
	uni.showModal({
		title: '提示',
		content: '请授权获取位置',
		showCancel: false,
		confirmText: '确认授权',
		success:() =>{
			wx.openSetting({
				success: (res)=>{
					console.log('###### openSetting ######', res)
					// res.authSetting = {
					// 	"scope.userLocationBackground": true
					// }
					this.getData()
				}
			})
		}
	})
},
errHandle(err){
	if(err){
		console.log('### err ###>>>>>>>>',err)
	} else {
		// 如果希望用户在最新版本的客户端上体验您的小程序,可以这样子提示
		this.$tip.alertBox('当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。')
	}

},

使用中如果报以下错误:
“startLocationUpdate:fail the api need to be declared in the requiredPrivateInfos field in app.json/ext.json”
首先确认小程序管理后台是否开通该相关api 权限。
然后,在项目根目录manifest.json文件中要有相关的配置,例:

 /* 快应用特有相关 */
    "mp-weixin" : {
        "appid" : "wx42952526c54cfb0b",
        "setting" : {
            "urlCheck" : false,
            "minified" : true,
            "postcss" : true
        },
        "usingComponents" : true,
        "permission" : {
            "scope.userLocation" : {
                "desc" : "获取当前位置"
            }
        },
        "requiredPrivateInfos" : [
            "getLocation",
            "startLocationUpdate",
            "onLocationChange",
            "startLocationUpdateBackground"
        ],
		"requiredBackgroundModes" : ["location"],
        "optimization" : {
            "subPackages" : true
        }
    },

如果忘记配置"requiredBackgroundModes" : [“location”],就不会出现 “使用小程序期间喝离开小程序后” 该选项
在这里插入图片描述

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值