getUserLocation() { let locations = {}//存放微信返回的坐标等信息 return new Promise((callback) => { let userGPS = ''//存放本机GPS状态值 this.getDeviceGPS()//获取本机GPS状态 if (locations == '') { //位置信息不存在,返回并提示 callback(true); return true; } //微信获取前后台坐标的接口:wx.startLocationUpdateBackground,这个接口申请开通后,需要搭配wx.onLocationChange来使用,使用时需要在app.json页面配置这两个接口 wx.startLocationUpdateBackground({ type: 'wgs84',//传参类型可以根据需求设置 success: (res) => { //判断是否也开通了wx.onLocationChange接口且检测本机GPS功能是否开启 if (wx.onLocationChange && this.userGPS != false) { wx.onLocationChange((res) => { callback(res);//返回结果里面包含的坐标信息对象 }); } }, fail: (err) => { if (err.errMsg == 'startLocationUpdateBackground:fail auth deny') { //未授权则返回false,另外弹窗提示。具体判断条件可以根据fail返回的内容来写 callback(false); } }, }); }); } // 获取本机设备的GPS信息 getDeviceGPS() { let system = wx.getSystemInfoSync(); //如果设备的GPS未开启,locationEnabled这里会返回false,以此判断 if (system.locationEnabled == false) { //GPS未开启,返回false this.userGPS = false return wx.showModal({ content: '请在系统设置中开启GPS定位权限', showCancel: false, confirmText: '确认', success: (res) => { console('res:',res) }, }) } else { //已开启,返回true this.userGPS = true } }
//app.json配置使用部分,具体配置也可以阅读官方文档:地理位置接口新增与相关流程调整 | 微信开放社区
"permission": {
"scope.userLocation": {
"desc": "您的位置将用于绑定您的区域"
}
},
"requiredPrivateInfos": [
"getLocation",
"onLocationChange",
"startLocationUpdateBackground"
],