1.在微信小程序中很多場景都需要用戶授權,例如用戶相冊權限,位置權限...,當需要將海報保存在相冊就會用到相冊權限(海報參考),在城市定位,店家列表由遠及近排序就會用到位置權限,這裏主要考慮位置權限使用場景。
2.主體思路,進頁面立馬彈出微信授權位置彈窗,提示用戶授權位置,授權成功則會獲取用戶地理經緯度座標,根據經緯度信息請求接口,獲取城市名稱。如果用戶拒絕授權,則拿不到用戶位置,展示未知(當然了,在現實開發中一般會有默認城市)。在旁邊放一個重新獲取按鈕,如果用戶授權過了就不用彈窗提示了,如果進頁面時用戶拒絕了,此時彈窗提示用戶是否授權,授權則打開授權頁面讓用戶授權,授權成功則會拿到用戶的位置。(因爲用戶的授權頁是通過wx.openSetting打開的新頁面,如果獲取位置的動作放在onload裏back回來後不會重新獲取,所以建議放onshow裏)。
3.代碼
3.1wxml
<view class='btn'>
<block wx:if="{{city}}">
<view>城市名</view>
</block>
<block wx:else>
未知
</block>
</view>
<view class='btn' catchtap='re_get_city'>重新獲取</view>
3.2wxss
.btn {
border: 1px solid #d6d6d6;
padding:5rpx 20rpx;
background: #fff;
color: #4d4d4d;
line-height: 50rpx;
font-size: 28rpx;
display: inline-block;
text-align: center;
margin: 10rpx;
}
3.3js
Page({
/**
* 頁面的初始數據
*/
data: {
city:''
},
/**
* 生命週期函數--監聽頁面加載
*/
onShow: function(options) {
var that = this;
// 放在onshow裏,當back回來後會執行該語句;如果放onload不會執行
that.get_city();
},
// 獲取用戶位置
get_city: function() {
var that = this;
wx.getLocation({
type: 'wgs84',
success: function(res) {
// 這裏會拿到一些授權信息,參數詳見官網
console.log(res);
if (res && res.latitude && res.longitude){
// 在這裏一般會通過後臺接口,通過經緯度比對獲取用戶當前城市名稱
that.setData({
city:'城市名'
})
}
}
})
},
/**重新定位**/
re_get_city: function() {
var that = this;
// 特別低的版本可能不能使用該方法,做一個兼容
if (!wx.getSetting) return
// 看看權限是否獲取,有權限,就直接拿值,如果沒有權限,打開授權頁
wx.getSetting({
success: function(res) {
console.log('getSetting...', res)
if (res.authSetting["scope.userLocation"] == true) {
// 有權限,拿值
that.get_city();
} else {
// 無權限,彈窗友好提示
wx.showModal({
title: '位置信息授權',
content: '位置授權暫未開啓,無法完成定位',
confirmText: '開啓授權',
cancelText: '仍然拒絕',
success: function(res) {
// 同意,打開授權頁
if (res.confirm) {
wx.openSetting({
success: (res) => {
if (res.authSetting["scope.userLocation"] == true) {
// 開關打開成功,獲取位置信息
that.get_city();
} else {
// 開關關閉,提示無法拿到位置權限
wx.showModal({
title: '提示',
content: '無法使用定位權限',
confirmText: '太遺憾了',
showCancel: false
})
}
},
fail: function() {
console.log('openSetting.failed')
}
})
}
// 不同意,彈窗提示無法拿到位置權限
if (res.cancel) {
wx.showToast({
title: '定位失敗',
icon: 'none',
duration: 1000
})
}
}
})
}
}
})
},
})
4.說明
4.1推薦地址:https://www.cnblogs.com/liuwei54/p/10911091.html
4.2推薦地址:https://www.jianshu.com/p/e232c3c9af37
4.3 官方 wx.getSetting 的 api 地址:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/setting/wx.getSetting.html
4.4 官方 wx.openSetting 的 api 地址:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/setting/wx.openSetting.html