微信小程序定位
相关 API 使用,查看微信官方文档
wx.getSetting ---> wx.authorize ---> wx.getLocation ---> GetAddressByLonAndLat()
###(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();
}
}
})
},
<br>
###(3)定位授权
####没有定位权限时,需要定位授权,代码如(2)中所示,定位授权框,如下图所示
<image src="https://img2018.cnblogs.com/blog/1649251/201911/1649251-20191112154216288-2056460748.png" width="500"></image>
####点击允许,则相当于初次开启定位权限,可以开始定位,点击不允许时,则关闭了定位权限,此时,界面上应该有按钮可再次触发去开启定位权限,“不允许”时,如下图所示
<image src="https://img2018.cnblogs.com/blog/1649251/201911/1649251-20191112154607160-670588531.png" width="500"></image>
####点击去授权,可以跳转至微信小程序官方权限设置界面
<image src="https://img2018.cnblogs.com/blog/1649251/201911/1649251-20191112160311113-1235850951.png" width="500"></image>
// button 触发位置授权
toOpenSetting(res) {
if(res.detail && res.detail.authSetting['scope.userLocation']) {
this.getLocation()
}
},
<br>
###(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,
})
}
})
},
####⚠️注意:wx.getLocation 返回的是经纬度坐标,因此必须使用第三方服务进行逆地址解析时,在解析时,需要确认第三方服务默认的坐标系,以便正确进行坐标转换

浙公网安备 33010602011771号