微信小程序获取用户位置信息,在此记录自己所使用的封装完成的函数
实现思路
- 调用
wx.getLocation
,获取用户授权 - 用户授权后,可获取到用户经纬度坐标
- 将获取到的用户经纬度坐标借助第三方转换为地理位置
注意事项
- 获取定位首先需要调用
wx.getLocation
去获取用户授权,这里有存在一个小坑,如果用户点击拒绝授权,wx.getLocation
下次则不会再出现提示框让用户去选择是否授权。 - 还存在用户已授权但是系统定位未开,获取不到经纬度,需提示用户打开定位。
代码
var QQMapwx = require("../../utils/qqmap-wx-jssdk.min.js");//引入qq位置服务js文件
usegetuseraddr(){
wx.showLoading({
title: '定位中',
});
//这里使用的qq地图转换经纬度坐标
var qqmapsdk,
that = this;
qqmapsdk = new QQMapwx({
key: 'GUQBZ-IWSWU-XXXXX-XXXXX-XXXXX-XXXXX' //自己在QQ地图申请的key
});
wx.getLocation({ // 调用`wx.getLocation `,获取用户授权
type: 'gcj02',
isHighAccuracy:true,
success (res) {//用户授权后,可获取到用户经纬度坐标
qqmapsdk.reverseGeocoder({
location:{
latitude:res.latitude,
longitude:res.longitude
},
success:function(ress){
that.setData({
useraddr : ress.result.formatted_addresses.recommend //成功将坐标转为地理位置并储存
});
app.globalData.useraddr=that.data.useraddr;
wx.showToast({
title: '定位成功',
icon: 'success',
duration: 500,
});
},
fail: function (res) {
wx.showToast({
title: '定位失败,请重试',
icon: 'none',
duration: 2000
});
},
});
},
fail: function () {
wx.hideLoading();
wx.getSetting({
success: function (res) {
if (!res.authSetting['scope.userLocation']) {
wx.showModal({
title: '',
content: '请允许XXXXX获取您的定位',
confirmText: '授权',
success: function (res) {
if (res.confirm) {
wx.openSetting();
} else {
console.log('get location fail');
}
}
})
}else {
//用户已授权,但是获取地理位置失败,提示用户去系统设置中打开定位
wx.showModal({
title: '',
content: '请在系统设置中打开定位服务',
confirmText: '确定',
success: function (res) {
}
})
}
}
})
}
})
}