微信小程序wx.onLocationChange使用与申请
由于wx. API测试环境频繁调用容易失败报错,官方推荐频繁调用定位场景下使用wx.,使用限制如图
下面是封装的方法
getWXLocation:() =>{wx.showLoading({title: '定位中...',mask: true,})return new Promise((resolve, reject) => {let _locationChangeFn = (res) => {resolve(res);wx.hideLoading()wx.offLocationChange(_locationChangeFn)}wx.startLocationUpdate({success: (res) => {wx.onLocationChange(_locationChangeFn)},fail: (err) => {console.log('获取当前位置失败', err)wx.hideLoading()reject()}})})}
下面是调用代码(方法名前记得加async)
let location = null;try {location = await getWXLocation();}catch(err){wx.showModal({cancelText: '取消',confirmText: '前往设置',content: '获取权限失败,需要获取您的地理位置才能为您提供更好的服务!是否授权获取地理位置?',editable: false,showCancel: true,title: '温馨提示',success: () => {that.toSetting()},fail: () => {},})return}
使用到的接口需要在app.json中声明,然后去 小程序后台设置申请 开发 =>开发管理 =>接口设置中申请,wx.不太好申请,本人申请了3次才过,前两次只有简单填了下申请理由,等了一天都申请失败了,后面去官方社区看了下申请通过的朋友咋弄的,就是申请理由尽可能详细,比如场景、原因。我写了使用场景,需要频繁调用,wx.容易失败,官方推荐使用wx.。下面录了视频,还贴了调用的部分代码,朋友们加油吧!!!
下面是app.json中的部分配置
"des": [""],
"": {
"scope.": {
"desc": "为了获取你的位置信息已确保你已处于设备位置附近"
},
"": ["", "","","",""]