微信小程序-獲取當前城市位置及再次受權地理位置

微信小程序-獲取當前城市位置html

 

1. 獲取當前地理位置,可經過wx.getLocation接口,返回經緯度、速度等信息;git

 注意---它的默認工做機制:json

 首次進入頁面,調用該api,返回用戶受權結果,並保持該結果。只要用戶未刪除該小程序或變動受權狀況,那麼用戶再次進入該頁面,受權結果仍是不變,且不會再次調用該API;小程序

 在不刪除小程序的狀況下,繼續再次發起受權請求,須要使用wx.openSetting。微信小程序

   因此第一步要拿到用戶的受權wx.openSettingapi

2. 第二步,可經過wx.getLocation接口,返回經緯度、速度等信息;微信

3. 微信沒有將經緯度直接轉換爲地理位置,可藉助騰訊位置服務中關於微信小程序的地理轉換JS SDK的API或者百度API (我使用的百度API)app

 

在用戶首次進入某頁面(須要地理位置受權)時候,在頁面進行在onShow時,進行調用wx.getLocation要求用戶進行受權;之後每次進入該頁面時,經過wx.getSetting接口,返回用戶受權具體信息。this

代碼以下:url

onShow: function () { var _this = this; //調用定位方法
 _this.getUserLocation(); }, //定位方法
getUserLocation: function () { var _this = this; wx.getSetting({ success: (res) => { // res.authSetting['scope.userLocation'] == undefined 表示 初始化進入該頁面
        // res.authSetting['scope.userLocation'] == false 表示 非初始化進入該頁面,且未受權
        // res.authSetting['scope.userLocation'] == true 表示 地理位置受權
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) { //未受權
 wx.showModal({ title: '請求受權當前位置', content: '須要獲取您的地理位置,請確認受權', success: function (res) { if (res.cancel) { //取消受權
 wx.showToast({ title: '拒絕受權', icon: 'none', duration: 1000 }) } else if (res.confirm) { //肯定受權,經過wx.openSetting發起受權請求
 wx.openSetting({ success: function (res) { if (res.authSetting["scope.userLocation"] == true) { wx.showToast({ title: '受權成功', icon: 'success', duration: 1000 }) //再次受權,調用wx.getLocation的API
 _this.geo(); } else { wx.showToast({ title: '受權失敗', icon: 'none', duration: 1000 }) } } }) } } }) } else if (res.authSetting['scope.userLocation'] == undefined) { //用戶首次進入頁面,調用wx.getLocation的API
 _this.geo(); } else { console.log('受權成功') //調用wx.getLocation的API
 _this.geo(); } } }) }, // 獲取定位城市
  geo: function () { var _this = this; wx.getLocation({ type: 'wgs84', success: function (res) { var latitude = res.latitude var longitude = res.longitude var speed = res.speed var accuracy = res.accuracy wx.request({ url: 'http://api.map.baidu.com/geocoder/v2/?ak=xxxxxxxxxxxx&location=' + res.latitude + ',' + res.longitude + '&output=json', data: {}, header: { 'Content-Type': 'application/json' }, success: function (ops) { console.log('定位城市:', ops.data.result.addressComponent.city) }, fail: function (resq) { wx.showModal({ title: '信息提示', content: '請求失敗', showCancel: false, confirmColor: '#f37938' }); }, complete: function () { } }) } }) }, 

 

效果圖:首次進入頁面

拒絕受權後,再次進入該頁面或者點擊頁面某按鈕(獲取位置)綁定JS

以上兩個彈出框的結構是同樣的,前者使用的是wx.getLocation接口自帶的樣式,後者使用的wx.showModel接口帶的樣式。

簡單講一下受權原理:首次進入該頁面,onshow調用wx.getLocation要求用戶進行受權;用戶拒絕後,再次進入該頁面,咱們經過wx.getSetting接口,返回用戶受權的狀況。

res.authSetting['scope.userLocation']的值與true比較,爲true就是受權了,false就是拒絕受權了。

 

詳見微信的scope表:https://mp.weixin.qq.com/debug/wxadoc/dev/api/authorize-index.html

 

來源:https://blog.csdn.net/weixin_42262436/article/details/80458430

相關文章
相關標籤/搜索