微信小程序-获取当前城市位置及再次受权地理位置

微信小程序-获取当前城市位置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

相关文章
相关标签/搜索