微信小程序获取地理位置授权,首先需要在app.json中添加配置:
"permission": {
"scope.userLocation": {
"desc": "请确认授权地理位置信息"
}
}
注意:获取经纬度:如果手机未开启位置信息,那么授权成功后在wx.getLocation()方法中也会一直失败,所以需要在fail方法中提示用户开启手机位置信息
下面代码里面的api.showToast是单独封装出来,其实都无所谓的看个人习惯
//获取地理信息
getUserLocation() {
let that = this
wx.getSetting({
success: (res) => {
// res.authSetting['scope.userLocation'] == undefined 初始化进入该页面,没有调用wx.getLocation这个方法的话,返回undefined
// res.authSetting['scope.userLocation'] == false 非初始化进入该页面,且未授权
// res.authSetting['scope.userLocation'] == true 地理位置授权
// 拒绝授权后再次进入重新授权
if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
// console.log('authSetting:status:拒绝授权后再次进入重新授权', res.authSetting['scope.userLocation'])
wx.showModal({
title:'提示',
content: '需要获取你的地理位置,请确认授权',
confirmColor:'#7FC241',
success(res) {
if (res.cancel) {
api.showToast('拒绝授权');
} else if (res.confirm) {
wx.openSetting({
success: function (dbs) {
if (dataAu.authSetting["scope.userLocation"] == true) {
//再次授权,调用wx.getLocation的API
that.getLocation(dbs)
} else {
api.showToast('授权失败')
}
},
})
}
},
})
}
// 初始化进入,未授权
else if (res.authSetting['scope.userLocation'] == undefined) {
// console.log('authSetting:status:初始化进入,未授权', res.authSetting['scope.userLocation'])
//调用wx.getLocation的API
that.getLocation(res)
}
// 已授权
else if (res.authSetting['scope.userLocation']) {
// console.log('authSetting:status:已授权', res.authSetting['scope.userLocation'])
//调用wx.getLocation的API
that.getLocation(res)
}
},
})
},
// 微信获得经纬度
getLocation (userLocation) {
let that = this
wx.getLocation({
type: "wgs84",
success: function (res) {
wx.openLocation({//使用微信内置地图查看位置。
latitude: res.latitude,//要去的纬度-地址
longitude: res.longitude,//要去的经度-地址
name: `地理位置信息`,
})
},
fail: function (res) {
if (res.errMsg === 'getLocation:fail:auth denied') {
api.showToast('拒绝授权')
}
if (!userLocation || !userLocation.authSetting['scope.userLocation']) {
// that.getUserLocation() //防止初次进来第一授权会弹出两个框,所以注释不用。
} else if (userLocation.authSetting['scope.userLocation']) {
wx.showModal({
title: '',
content: '请在系统设置中打开定位服务',
showCancel: false,
success: result => {
}
})
} else {
api.showToast('授权失败')
}
}
})
},
开发工具上地址打开地图有偏差,在真机预览就不会有偏差
网友评论