在微信小程序开发中,很多时候要用到定位信息,特别是某些基于位置提供服务的小程序,没有定位就无法提供相应功能。在实际业务中,主要要考虑下面两点:
1、在小程序中,如果用户首次拒绝了位置授权,那么再通过wx.getLocation
获取位置信息时,是会直接走fail回调的。此时如果还想弹出授权,需要通过wx.openSetting
调用设置位置授权功能。
2、当手机没有开启GPS定位服务时,这时候也应该给用户友好的提示,如果继续使用需要打开手机GPS定位功能。
下面代码是基于uniapp写的,如果使用小程序原生开发,uni都改为wx即可,api都是一样的。在获取位置授权时,可以直接调用getLocation
方法。
// 获取当前位置经纬度
handleLoacation(toast) {
uni.getLocation({
type: 'gcj02',
success: res => {
console.log('success')
// 获取到经纬度后根据实际业务做处理,下面业务逻辑仅供参考
// 1、先把经纬度存入缓存中
this.setLocation(res)
// 2、获取到经纬度后再请求对应数据
this.getData()
},
fail: err => {
// 判断是否获取到了定位
// this.isLocation = false
// 根据不同需求做了两种类型提示,需要根据实际业务修改
if (toast) {
// this.$u.toast是用的框架里封装的弹出消息
this.$u.toast('您已拒绝授权,相关功能会无法使用!')
return
}
//用户已授权,但是获取地理位置失败,提示用户去系统设置中打开定位
uni.showModal({
title: '提示',
content: '请在系统设置中打开定位服务,重新进入小程序!'
})
}
})
},
// 定位获取位置信息授权逻辑
getLocation() {
//wx.getSetting是获取用户授权的信息的,除了应用在位置信息授权还能应用在用户信息授权等等
uni.getSetting({
success: res => {
// true说明已经授权,如果还拿不到定位信息,说明用户的手机没开启定位功能
if (res.authSetting['scope.userLocation'] === true) {
console.log('已经授权,非第一次')
//授权后默认加载,直接获取定位
this.handleLoacation()
}
// scope.userLocation === undefined代表用户未授权且第一次登陆
else if (res.authSetting['scope.userLocation'] === undefined) {
// 如果用户是第一次登陆且未授权的情况,会直接弹窗请求授权
// 使用 getlocation 获取用户 经纬度位置
console.log('第一次登陆且未授权')
this.handleLoacation(true)
}
// 小程序检测到用户不是第一次进入该页面,且未授权
else if (res.authSetting['scope.userLocation'] !== undefined && res.authSetting['scope.userLocation'] !== true) {
console.log('不是第一次进入该页面,且未授权')
uni.showModal({
title: '是否授权当前位置',
content: '需要获取您的地理位置,请确认授权,否则无法相关功能!',
success: res => {
//如果点击取消则显示授权失败
if (res.cancel) {
this.$u.toast('您已拒绝授权!')
}
//如果点击确定会打开授权页请求二次授权
else if (res.confirm) {
uni.openSetting({
success: dataAu => {
if (dataAu.authSetting['scope.userLocation'] === true) {
this.$u.toast('授权成功!')
//再次授权,调用getLocationt的API
this.handleLoacation()
} else {
// this.isLocation = false
this.$u.toast('授权失败!')
}
}
})
}
}
})
}
},
fail: err => {
// this.isLocation = false
uni.showModal({
title: '提示',
content: '未知错误,请重新打开小程序!'
})
}
})
},