寫在前面我們知道: 1、微信的getLocation接口,是獲取用戶當(dāng)前地理位置的,返回經(jīng)緯度、速度等信息; 2、它的默認(rèn)工作機制: 首次進(jìn)入頁面,調(diào)用該api,返回用戶授權(quán)結(jié)果,并保持該結(jié)果。 只要用戶未刪除該小程序或 ...
寫在前面我們知道:
1、微信的getLocation接口,是獲取用戶當(dāng)前地理位置的,返回經(jīng)緯度、速度等信息;
2、它的默認(rèn)工作機制:
首次進(jìn)入頁面,調(diào)用該api,返回用戶授權(quán)結(jié)果,并保持該結(jié)果。
只要用戶未刪除該小程序或變更授權(quán)情況,那么用戶再次進(jìn)入該頁面,
授權(quán)結(jié)果還是不變,且不會再次調(diào)用該API;
3、那么問題來了:如何不要求用戶刪除小程序情況下,再次發(fā)起授權(quán)請求呢?
KEY:wx.openSetting
1、效果圖:首次進(jìn)入某頁面

拒絕授權(quán)后,再次進(jìn)入該頁面或者點擊頁面某按鈕(獲取位置)綁定JS

2、不知道有沒有細(xì)心的道友,發(fā)現(xiàn)上面2個彈出框的結(jié)構(gòu)是一樣的,前者使用的是wx.getLocation接口自帶的樣式,后者使用的wx.showModel接口帶的樣式
3、廢話不多說,簡單講一下原理:首次進(jìn)入該頁面,onload或者onshow調(diào)用wx.getLocation要求用戶進(jìn)行授權(quán);用戶拒絕后,再次進(jìn)入該頁面,我們通過wx.getSetting接口,返回用戶授權(quán)的情況:

然后,根據(jù)上面JS中,res.authSetting['scope.userLocation']的值與true比較,為true就是授權(quán)了,false就是拒絕授權(quán)了。
我們這里考慮的是拒絕授權(quán),再調(diào)用wx.openSetting接口,請求再次授權(quán),返回授權(quán)結(jié)果處理數(shù)據(jù)和業(yè)務(wù)。over,就是這么EASY!
4、我這里只打印出了userInfo和userLocation的接口返回信息,當(dāng)然你還可以打印其他的信息,只要你之前調(diào)用過這些微信API,詳見微信的scope表:https://mp.weixin.qq.com/debug/wxadoc/dev/api/authorize-index.html

5、詳情代碼:
//地圖功能單獨拿出來 -xzz1023
var village_LBS = function(that){
//var that = this;
// ------------ 騰訊LBS地圖 --------------------
wx.getLocation({
type: 'gcj02', //返回可以用于wx.openLocation的經(jīng)緯度
success: function (res) {
// 調(diào)用接口, 坐標(biāo)轉(zhuǎn)具體位置 -xxz0717
demo.reverseGeocoder({
location: {
latitude: Number(res.latitude),
longitude: Number(res.longitude)
},
success: function (res) {
console.log(res);
that.setData({
start_address: res.result.address, //起點地址
city: res.result.address_component.city, //起點城市
district: res.result.address_component.district //區(qū)
})
}
});
})
)
Page({
onLoad: function (options) {
var that = this;
village_LBS(that);
}
onReady: function () {
var that = this;
wx.getSetting({
success: (res) => {
console.log(res);
console.log(res.authSetting['scope.userLocation']);
if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {//非初始化進(jìn)入該頁面,且未授權(quán)
wx.showModal({
title: '是否授權(quán)當(dāng)前位置',
content: '需要獲取您的地理位置,請確認(rèn)授權(quán),否則地圖功能將無法使用',
success: function (res) {
if (res.cancel) {
console.info("1授權(quán)失敗返回數(shù)據(jù)");
} else if (res.confirm) {
//village_LBS(that);
wx.openSetting({
success: function (data) {
console.log(data);
if (data.authSetting["scope.userLocation"] == true) {
wx.showToast({
title: '授權(quán)成功',
icon: 'success',
duration: 5000
})
//再次授權(quán),調(diào)用getLocationt的API
village_LBS(that);
}else{
wx.showToast({
title: '授權(quán)失敗',
icon: 'success',
duration: 5000
})
}
}
})
}
}
})
} else if (res.authSetting['scope.userLocation'] == undefined) {//初始化進(jìn)入
village_LBS(that);
}
}
})
}
})