1.配置 ---manifest.json/源码视图/"mp-weixin"里面添加以下配置
在全局定义一个变量 表示开启后台定位功能的标识 ---在main.js里面定义positionTimer
"permission" : {
"scope.userLocation" : {
"desc" : "获取配送地址"
}
},
"requiredPrivateInfos" : [
"getLocation",
"chooseLocation",
"onLocationChange",
"startLocationUpdate",
"startLocationUpdateBackground"
],
"requiredBackgroundModes" : [ "location" ], //需要再后台使用
2.在需要配送员抢单的地方调用
//确认抢单
sureOrderBtn() {
var that = this;
//开启后台小程序也定位功能
wx.startLocationUpdateBackground({
if (Vue.prototype.positionTimer == null) {
wx.startLocationUpdateBackground({
success(res) {
Vue.prototype.positionTimer = setInterval(function() {
let data = {
lat: '',
lng: ''
}
const _locationChangeFn = function(res) {
data.lat = res.latitude;
data.lng = res.longitude
console.log('这里调用向后端发送经纬度的接口',data)
wx.offLocationChange(_locationChangeFn)
}
wx.onLocationChange(_locationChangeFn)
}, 30000)
},
fail(res) {
console.log('开启后台定位失败', res);
//授权失败后引导用户打开定位信息
this.openSetting();
}
})
}
},
fail(res) {
console.log('开启后台定位失败', res);
//授权失败后引导用户打开定位信息
this.openSetting();
}
});
},
//定位授权弹框
openSetting(){
wx.getSetting({
success: function(res) {
var statu = res.authSetting;
if (!statu["scope.userLocationBackground"]) {
wx.showModal({
title: "请授权使用期间和离开后的位置!",
content: "需要获取您的地理位置,请确认授权,否则地图功能将无法使用",
success: function(tip) {
if (tip.confirm) {
wx.openSetting({
success: function(data) {
if (data.authSetting[
"scope.userLocationBackground"
] === true) {
}
}
});
} else {
//console.log('用户拒绝打开设置界面')
}
}
});
}
}
});
}
注意:在小程序退出后台后该定位功能还是能正常向后端发送经纬度的,但是如果杀掉小程序就不会再调用了,故:可以在开启小程序的时候判断是否有在配送的物品,如果有就自动再调起sureOrderBtn里面的方法