微信小程序定位权限封装
getUserOrSystemPermissions.js
//如需动态获取权限,修改res.authSetting['scope.userLocation']与scope: 'scope.userLocation'的值。
const getLocation = () => {
return new Promise((resolve, reject) => {
wx.getSystemInfo({
success(res) {
var isSystemLocatioon = res.locationAuthorized;
if (isSystemLocatioon == false) {
wx.showModal({
title: '提示',
content: '请授权微信定位权限,\n前往【设置】中开启',
showCancel: false,
success(res) {
if (res.confirm) {
reject()
}
}
})
} else {
wx.getSetting({
success(res) {
if (!res.authSetting['scope.userLocation']) {
wx.authorize({
scope: 'scope.userLocation',
success() {
resolve()
},
fail(e) {
wx.showModal({
title: '提示',
content: '请前往设置打开权限',
success(res) {
if (res.confirm) {
wx.openSetting({
success(res) {
resolve()
},
fail(err) {
reject()
}
})
} else if (res.cancel) {
wx.showModal({
title: '提示',
content: '请授权小程序定位权限,\n「右上角」-「设置」中开启',
showCancel: false,
success(res) {
if (res.confirm) {
reject()
}
}
})
}
}
})
}
})
} else {
resolve()
}
}
})
}
}
})
})
}
module.exports = {
getLocation,
}
get_address.js
var getUOSPermissions = require("../../utils/getUserOrSystemPermissions.js")
onLoad: function (options) {
getUOSPermissions.getLocation().then(res => {
that.setData({})
wx.getLocation({
type: 'wgs84', //返回可以用于wx.openLocation的经纬度
success(res) {
that.setData({
latitude: res.latitude,
longitude: res.longitude
})
}
})
}).catch(e => {
console.log("异常:", e);
})
}
}
app.json
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序位置接口"
}
}