isOpenLocationAuth: 0 // 是否有定位权限 0定位中 1定位成功 2定位失败 3定位禁止
onShow() {
wx.showLoading({
title: '定位中'
})
this.getLocationAuth();
},
getLocationAuth() {
// wx.getSetting 获取设置
wx.getSetting({
success: res => {
// 是否有定位权限
if(!res.authSetting["scope.userLocation"]) {
wx.hideLoading();
// 没有权限则通过 wx.authorize 授权
wx.authorize({
scope: 'scope.userLocation',
success: res => {
this.getLocation();
},
fail: () => {
wx.hideLoading();
this.setData({
isOpenLocationAuth: 2, // 定位失败
})
}
})
} else {
this.getLocation();
}
}
})
},
<text class="text_red">暂时无法获取当前位置</text>
<button open-type="openSetting" bindopensetting="toOpenSetting">去授权</button>
// button 触发位置授权
toOpenSetting(res) {
if(res.detail && res.detail.authSetting['scope.userLocation']) {
this.getLocation()
}
},
getLocation() {
wx.showLoading({
title: '定位中',
})
// wx.getLocation 定位
wx.getLocation({
type: 'gcj02', // wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标
success: res => {
this.setData({
chooseLatitude: res.latitude,
chooseLongitude: res.longitude,
isOpenLocationAuth: 1 // 定位成功
})
this.GetAddressByLonAndLat(res.longitude, res.latitude); // 经纬度转地址
wx.hideLoading();
},
fail: () => {
wx.hideLoading();
this.setData({
isOpenLocationAuth: 3,
})
}
})
},
原文:https://www.cnblogs.com/Pecci/p/11842753.html