微信小程序获取用户当前位置有三个方式:
1. wx.getLocation
注意: 先要在app.json里配置permission:
不然就会出现以下提示(本地测试环境):
配置如下:
"permission": {"scope.userLocation": {"desc": "为了给您提供更好的服务,请授权您的地理位置信息"}},
wxml:
<button class="btn" type="primary" bindtap="handleGetLocation">getLocation
</button>
js:
handleGetLocation: function () {//获取位置wx.getLocation({type: 'gcj02', //默认为 wgs84 返回 gps 坐标,gcj02 返回可用于wx.openLocation的坐标success: (res) => {console.log(res)},fail: (err) => {console.log(err)}})},
success回调函数返回数据:
2.wx.chooseLocation
wxml:
<button class="btn" type="default" bindtap="handleChooseLocation">chooseLocation
</button>
js:
handleChooseLocation: function () {wx.chooseLocation({success: (res) => {console.log(res)let {latitude, longitude, name} = resthis.setData({hasLocation: true,latitude, longitude, name})},fail: (err) => {console.log(err)}});},
打开地图效果:
选择完地址 success回调函数返回数据:
3.wx.openLocation
wxml:
<button class="btn" type="default" bindtap="handleChooseLocation">chooseLocation
</button>
<button class="btn" wx:if="{{hasLocation}}" type="warn" bindtap="handleOpenLocation">openLocation
</button>
js:
handleOpenLocation: function () {let {latitude, longitude, name} = this.datawx.openLocation({latitude,longitude,name,scale: 28}) },
打开地图效果:
授权方法有三种:
1. wx.getSetting
js:
wx.getSetting({success (res) {console.log(res.authSetting)}})
输出结果如下:
2. wx.openSetting
调起权限设置选择界面,设置界面只会出现小程序已经向用户请求过的权限,如下面:
3. wx.authorize
onShow: function () {//初始获取定位权限wx.authorize({scope: 'scope.userLocation',success: (res) => {console.log(res)},fail: (err) => {console.log(err)}})},
说下一个常见场景,用户不允许授权地理位置信息,在后续操作中又需要授权才能使用地图,如何处理:
可以在fail里弹对话框:
wxml:
<button class="btn" type="default" bindtap="onChooseLocation">chooseLocation
</button>
js:
handleChooseLocation: function() {wx.chooseLocation({success: (res) => {console.log(res)let {latitude, longitude, name} = resthis.setData({hasLocation: true,latitude, longitude, name})},fail: (err) => {console.log(err)}});},onChooseLocation: function () {let self = this;wx.getSetting({success: (res) => {if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] == true) {self.setData({position: true,})//获取当前位置self.handleChooseLocation();} else {//未授权wx.showModal({title: '请求授权当前位置',content: '需要获取您的地理位置,请确认授权',success: function (res) {if (res.cancel) {//取消授权wx.showToast({title: '拒绝授权',icon: 'none',duration: 1000})} else if (res.confirm) {//确定授权,通过wx.openSetting发起授权请求wx.openSetting({success: function (res) {if (res.authSetting["scope.userLocation"] == true) {// wx.showToast({// title: '授权成功',// icon: 'success',// duration: 1000// })//再次授权,调用wx.getLocation的APIself.handleChooseLocation();} else {// wx.showToast({// title: '授权失败',// icon: 'none',// duration: 1000// })}}})}}})}},fail(res) {console.log(res)}}) },
参考资料:
授权 | 微信开放文档
微信小程序之获取用户位置权限(拒绝后提醒) - 站住,别跑 - 博客园