uniapp中wx.startLocationUpdateBackground切换到后台仍能间隔上报当前位置

1.在manifest.json中修改

"mp-weixin" : {
	"appid" : "*******",//自己的appid
	"setting" : {
		"urlCheck" : false
	},
	"usingComponents" : true,
	"requiredPrivateInfos" : [ 
		"chooseLocation", 
		"getLocation",
		"onLocationChange",//配合startLocationUpdateBackground获取当前经纬度
		"startLocationUpdateBackground" //必填
	],
    //加上"location"是为了在权限设置里面增加“使用小程序期间和离开小程序后”
    //获取权限默认选项是“在使用小程序期间”,不能默认“使用小程序期间和离开小程序后”,需要用户自己选择
	"requiredBackgroundModes": ["location"],//必填
	"permission" : {
		"scope.userLocation" : {
			"desc" : "你的位置信息将用于小程序位置接口的效果展示"
		}
	}
},

2.在你所需要添加的页面增加一下代码

getRealTimeLocaltion(){
	this.getDeviceGPS()//获取本机GPS状态
	wx.startLocationUpdateBackground({
		type: 'wgs84',
		success: (res) => {
			this.getBackgroundLocation();
		},
		fail: (err) => {
			//授权失败后引导用户打开定位信息
			uni.getSetting({
				success: (res) => {
					var statu = res.authSetting;
					if (!statu["scope.userLocationBackground"]) {
						uni.showModal({
							title: "是否授权在使用期间和离开后!",
							content: "需要获取您当前的位置信息,请在位置信息中选择",
							success: (tip) => {
								if (tip.confirm) {
									uni.openSetting({
										success: (data)=> {
											if (data.authSetting["scope.userLocationBackground"] == true) {
												this.getBackgroundLocation();
											}
										}
									});
								} else {
									console.log('用户拒绝打开设置界面')
								}
							}
						});
					}
				}
			});
		}
	});
},
// 获取本机设备的GPS信息
getDeviceGPS() {
	let system = uni.getSystemInfoSync();
	//如果设备的GPS未开启,locationEnabled这里会返回false,以此判断
	if (system.locationEnabled == false) {
		//GPS未开启,返回false
		this.userGPS = false
		return uni.showModal({
			content: '请在系统设置中开启GPS定位权限',
			showCancel: false,
			confirmText: '确认',
			success: (res) => {
				console.log('res:',res)
			},
		})
	} else {
		//已开启,返回true
		this.userGPS = true
	}
},
getBackgroundLocation() {
	//判断是否也开通了wx.onLocationChange接口且检测本机GPS功能是否开启,GPS不开启不会间接获取
	if (wx.onLocationChange && this.userGPS != false) {=
		wx.onLocationChange((data) => {
            //微信开发工具上面只能触发一次,真机上面是循环获取
            //设置一个公共时间,原因是时间间隔太短,自己设置时间,然后去操作相应的逻辑
			if (this.time == 11){
				// 调取实时位置
				this.reportLocation(this.location);
				this.time = 0;
			}
			this.time ++;
			this.location = data;
		});
	}
},
//调取位置后的操作逻辑
reportLocation(){
    
}

 

posted @ 2023-05-18 11:13  mm789  阅读(1522)  评论(0)    收藏  举报