####相關 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 返回的是經緯度坐標,因此必須使用第三方服務進行逆地址解析時,在解析時,需要確認第三方服務默認的坐標系,以便正確進行坐標轉換