相关 API 使用,查看微信官方文档
(写在前面)流程:
wx.getSetting ---> wx.authorize ---> wx.getLocation ---> GetAddressByLonAndLat()
wx.getSetting ---> wx.authorize ---> wx.getLocation ---> GetAddressByLonAndLat()
(1)定义参数
定义一个参数 isOpenLocationAuth ,方便区分 定位成功 与 定位失败 的各种情况,以便在界面上作出不同情况相应的展示
isOpenLocationAuth: 0 // 是否有定位权限 0定位中 1定位成功 2定位失败 3定位禁止
(2)判断是否有定位功能权限
当触发定位事件后,首先需要判断是否有定位功能权限,有则直接定位,没有则授权
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();
}
}
})
},
(3)定位授权
没有定位权限时,需要定位授权,代码如(2)中所示,定位授权框,如下图所示
点击允许,则相当于初次开启定位权限,可以开始定位,点击不允许时,则关闭了定位权限,此时,界面上应该有按钮可再次触发去开启定位权限,“不允许”时,如下图所示
点击去授权,可以跳转至微信小程序官方权限设置界面
<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()
}
},
(4)定位
有定位权限后,可以通过定位获取当前地址
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,
})
}
})
},