0. 效果展示
初次授权:
拒绝后再次进入:
1. 全局配置
app.json文件配置
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序位置接口的效果展示"
}
},
"requiredPrivateInfos": [
"getLocation"
]
2. 代码展示
组件内使用
onLoad(options) {
this.getSetting()
}
// 校验是否授权定位
getSetting() {
wx.getSetting({
success: (res) => {
let authSetting = res.authSetting
if (authSetting['scope.userLocation'] || authSetting['scope.userLocation'] == undefined) {
// 已授权 || 尚未进行操作
this.getLocation()
} else {
// 曾拒绝授权,需主动前往进行授权
wx.showModal({
title: '您未开启地理位置授权',
content: '是否前往授权?',
success: res => {
if (res.confirm) {
wx.openSetting()
}
}
})
}
}
})
},
// 获取位置信息
getLocation() {
wx.getLocation({
altitude: 'altitude',
highAccuracyExpireTime: 0,
isHighAccuracy: true,
type: 'type',
success: (result) => {
const {
latitude,
longitude
} = result
// 通过接口置换定位信息进行展示
app.http.request('/get-location', {
latitude,
longitude
}).then(res => {
this.setData({
address: res.data
})
})
},
fail: (err) => {
wx.showToast({
icon: 'error',
title: '太频繁啦~',
})
},
})
},
页面内展示:
<!-- 展示定位地址,点击可再次进行定位获取 -->
<view class="address_tag flex flex_center" catchtap="getSetting">
<text>{{address}}</text>
</view>