项目使用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文件中要有相关的配置,例:文章来源:https://www.toymoban.com/news/detail-502593.html
/* 快应用特有相关 */
"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”],就不会出现 “使用小程序期间喝离开小程序后” 该选项
文章来源地址https://www.toymoban.com/news/detail-502593.html
到了这里,关于wx.startLocationUpdateBackground和wx.onLocationChange的结合使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!