首先,在page外定义一个公共函数用于发送获取位置的请求
var getLocation = function (that) { wx.getLocation({ type: \'wgs84\', success: function (res) { // 经纬度 var latitude = res.latitude var longitude = res.longitude var aK = that.data.aK wx.request({ url: \'https://api.map.baidu.com/geocoder/v2/?ak=\' + aK + \'&location=\' + latitude + \',\' + longitude + \'&output=json\', data: {}, header: { \'content-type\': \'application/json\' }, success: function (res) { var city = res.data.result.addressComponent.city; that.setData({ currentCity: city }) wx.request({ url: \'xxx\' + city, data: {}, header: { \'content-type\': \'application/json\' }, success: function (res) { that.setData({ county: res.data, }) }, }) } }) }, fail: function () { wx.showToast({ title: \'授权失败\', icon: \'success\', duration: 1000 }) } }) }
然后,在page中需要位置调用page外部的getLocation 函数
wx.getSetting({ success: (res) => { if (res.authSetting[\'scope.userLocation\'] != undefined && res.authSetting[\'scope.userLocation\'] != true) {//非初始化进入该页面,且未授权 wx.showModal({ title: \'是否授权当前位置\', content: \'需要获取您的地理位置,请确认授权,否则无法获取您所需数据\', success: function (res) { if (res.cancel) { that.setData({ isshowCIty: false }) wx.showToast({ title: \'授权失败\', icon: \'success\', duration: 1000 }) } else if (res.confirm) { wx.openSetting({ success: function (dataAu) { if (dataAu.authSetting["scope.userLocation"] == true) { wx.showToast({ title: \'授权成功\', icon: \'success\', duration: 1000 }) //再次授权,调用getLocationt的API getLocation(that); } else { wx.showToast({ title: \'授权失败\', icon: \'success\', duration: 1000 }) } } }) } } }) } else if (res.authSetting[\'scope.userLocation\'] == undefined) {//初始化进入 getLocation(that); } else { //授权后默认加载 getLocation(that); } } })
上述过程执行顺序为:
1.先加载wx.getLocation弹出自己的授权框,如图
然后,点击确定即可授权,若点击取消则取消授权,当再次需要授权时,会调用我们自定义的Modal框,如图
其次,针对上述的Modal框点击取消则关闭,若点击确定则打开手机的地址授权设置,如图
最后,若直接点击左上方的返回箭头则取消授权,若先选中地理位置按钮,然后在点击左上方的返回箭头则授权成功,如图