本篇文章记录一下最近遇到的微信小程序再用wx.chooseLocation无效直接进入fail的问题
此问题是因为第一次提示授权时用户选择了取消导致的。现在是调用前需要先验证一下是否授权
一、wxml文件代码 调用getLocation函数
<view class="cu-form-group" bind:tap="getLocation">
<view class="title">商家地址</view>
</view>
二、getLocation函数验证并提示授权后调用onGetLocation方法
//验证是否授权
getLocation: function () {
let _this = this;
wx.getSetting({
success(res) {
// 判断定位的授权
if (!res.authSetting['scope.userLocation']) {
wx.authorize({
scope: 'scope.userLocation',
success() {
_this.onGetLocation();
},
fail(errMsg) {
wx.showToast({ title: JSON.stringify(errMsg), icon: 'none' })
}
})
} else {
_this.onGetLocation();
}
}
})
},
//打开地图获取位置
onGetLocation: function (e) {
console.log('选择位置后的 :>> ', e);
wx.chooseLocation({
success: (result) => {
console.log('选择位置后的 :>> ', result);
},
fail: (e) => {
},
complete: () => { }
});
},