最新做过的一个微信小程序进行了迭代优化,获取用户地理位置这块儿的功能就进行了优化,再贴一下优化的代码。
主要是做了一下用户拒绝授权地理位置的处理,以及如何在用户拒绝授权后再次引导用户打开设置页面进行再次授权处理。
wxml:
<view class="location">
<view class="header">
<image class="img-navigation" src="/images/location.png"></image>
<view class="rescue-position">呼救位置</view>
</view>
<view class="coordinate">
<picker mode="region" bindchange="bindRegionChange" class="address-picker" value="{{ region }}">{{ region[0] }}-{{ region[1] }}-{{ region[2] }}</picker>
<input value="{{ info.address }}" data-inputitem="address" placeholder="请输入当前具体位置" placeholder-class="placeholder" class="address-input" bindblur="infoInput" />
</view>
</view>
data:
region: ['北京市', '北京市', '丰台区']
方法:
省市区选择器变化:
// 省市区选择器变化
bindRegionChange: function (e) {
console.log('picker发送选择改变,携带值为', e.detail.value)
this.setData({
region: e.detail.value
})
},
获取当前地理位置
// 获取当前位置坐标并解析
getLocation() {
console.log('getLocation')
let that = this
let qqmapsdk = new QQMapWX({
key: '你自己申请的key' // 必填
})
// 获取当前地理位置
wx.getLocation({
// 国内只能使用gcj02坐标系,wgs84不能使用;高德地图等都是使用的gcj02
type: 'gcj02',
success: function (res) {
// 坐标纠偏
wx.request({
url: 'https://apis.map.qq.com/ws/coord/v1/translate', // 官方地址
method: 'GET',
data: {
type: 5,
locations: `${res.latitude},${res.longitude}`,
key: '你自己申请的key'
},
success: res => {
// 将地理坐标转换为度分秒形式
that.data.info.lon = that.cacuLonLat(res.data.locations[0].lng)
that.data.info.lat = that.cacuLonLat(res.data.locations[0].lat)
// 解析地理坐标获取实际位置
qqmapsdk.reverseGeocoder({
location: {
longitude: res.data.locations[0].lng,
latitude: res.data.locations[0].lat
},
success: function(res) {
console.log(res, 'res')
let province = res.result.address_component.province
let city = res.result.address_component.city
let district = res.result.address_component.district
that.data.info.address = res.result.formatted_addresses.recommend
that.setData({
info: that.data.info,
region: [province, city, district],
hasSubmited: false
})
}
})
}
})
},
fail: res => {
if (res.errMsg !== 'getLocation:fail:timeout') {
console.log('获取定位失败', res)
util.WXToast('请手动输入当前位置')
that.setData({
hasSubmited: false
})
}
}
})
},
每次进入页面时, 判断是否授权了地理位置(这里删除了一些业务逻辑代码,不影响地理位置的授权):
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
console.log('onShow')
let that = this
// 判断网络状态
util.judgeNetwork(this) // 自己根据官方提供的方法进行封装的,加了一些提示文案、
// 判读用户是否已授权获取定位
wx.getSetting({
success: res => {
// 已授权
if (res.authSetting['scope.userLocation']) {
console.log('已授权定位')
that.getLocation()
} else if (res.authSetting['scope.userLocation'] === undefined) {
console.log('初次授权定位')
// 尚未授权
that.getLocation()
} else if (res.authSetting['scope.userLocation'] === false) {
console.log('拒绝授权定位')
util.WXModel('无法获取当前位置,请手动开启授权', true, () => {
wx.openSetting({
success: function (data) {
if (data.authSetting['scope.userLocation']) {
console.log('打开设置授权定位')
that.getLocation()
}
}
})
}, () => {
util.WXToast('请手动输入当前位置')
})
}
}
})
},