您好,欢迎访问一九零五行业门户网

微信小程序实例:获取当前城市位置及再次授权地理位置的代码实现

本篇文章给大家带来的内容是关于微信小程序实例:获取当前城市位置及再次授权地理位置的代码实现,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
1. 获取当前地理位置,可通过wx.getlocation接口,返回经纬度、速度等信息;
 注意---它的默认工作机制:
 首次进入页面,调用该api,返回用户授权结果,并保持该结果。只要用户未删除该小程序或变更授权情况,那么用户再次进入该页面,授权结果还是不变,且不会再次调用该api;
 在不删除小程序的情况下,继续再次发起授权请求,需要使用wx.opensetting。
   所以第一步要拿到用户的授权wx.opensetting;
2. 第二步,可通过wx.getlocation接口,返回经纬度、速度等信息;
3. 微信没有将经纬度直接转换为地理位置,可借助腾讯位置服务中关于微信小程序的地理转换js sdk的api或者百度api (我使用的百度api)
在用户首次进入某页面(需要地理位置授权)时候,在页面进行在onshow时,进行调用wx.getlocation要求用户进行授权;以后每次进入该页面时,通过wx.getsetting接口,返回用户授权具体信息。
代码如下:
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就是拒绝授权了。
 相关推荐:
小程序利用setdata修改数组中的某一个值的实现
 小程序中实现选择预览图片同时可以实现长按删除图片的代码
 微信小程序--树莓派(raspberry pi)小车控制的代码流程
以上就是微信小程序实例:获取当前城市位置及再次授权地理位置的代码实现的详细内容。
其它类似信息

推荐信息