最近使用小程序获取当前的地理位置,提示“getLocation须要在app.json中声明permission字段”,而后在app.json中增长permission属性配置:git
"permission": { "scope.userLocation": { "desc": "你的位置信息将用于小程序位置接口的效果展现" } },
用户首次进入获取其地理位置信息要先通过受权,若是用户赞成将成功获取到其地理位置,而后页面显示一个‘获取位置信息’按钮,点击后跳到地图并标识其当前所在位置;若是开始受权时用户拒绝了,那么页面会显示一个‘受权并获取位置信息’按钮,用户点击后会跳到受权设置页面,须要进行手动设置,设置后根据结果,若是设置了赞成那么返回后显示地图上的其所在位置,若是没有设置赞成返回后仍是显示‘受权并获取位置信息’按钮。json
wxml:小程序
<button wx:if="{{isLocation}}" bindtap='Location'>获取位置信息</button>
<button wx:else open-type="openSetting" bindopensetting='bindopensetting'>点击受权并获取位置信息</button>
js:app
data:{ isLocation: false }, /** * 生命周期函数--监听页面加载 */ onLoad: function(options){
var that = this;
//弹出受权用户确认后获取其地理位置 wx.getLocation({ type: 'wgs84', success: function (res) { var latitude = res.latitude var longitude = res.longitude that.setData({ isLocation: true, latitude: latitude, longitude: longitude }) }, fail: function (res) { console.log('拒绝受权') that.setData({ isLocation: false }) } }) }, //获取位置信息 Location: function (e) { wx.openLocation({ latitude: this.data.latitude, longitude: this.data.longitude, scale: 18 }) }, //手动设置受权 bindopensetting: function (e) { var that = this; if (!e.detail.authSetting['scope.userLocation']) { that.setData({ isLocation: false }) } else { that.setData({ isLocation: true, }) wx.getLocation({ type: 'wgs84', success: function (res) { var latitude = res.latitude var longitude = res.longitude that.setData({ latitude: latitude, longitude: longitude }) wx.openLocation({ latitude: latitude, longitude: longitude, scale: 18 }) } }) } },
用户首次进入经过onload 中的 wx.getLocation弹框受权位置,若是赞成isLocation设置为true并保存位置信息,这时页面直接显示“获取位置信息”按钮,点击后经过Location事件直接打开地图,经过开始赞成受权后保存的经纬度显示当前位置。 若是用户第一次拒绝了受权,那么isLocation设置为false,显示的是“点击受权并获取位置信息”按钮,这时这个button按钮的设置方式open-type=“openSetting” bindopensetting=‘bindopensetting’,用按钮的open-type发起打开受权设置页,bindopensetting是设置用户设置受权以后的回调,咱们可在回调里判断用户勾没勾选赞成受权,若是判断赞成了,那么isLocation设置为true,以后显示的都是“获取位置信息”,没必要受权直接显示地图;若是没有勾选赞成那么isLocation设置是false,以后再通过这个页面仍是显示“点击受权并获取位置信息”。最后注意的是在回调里能够用回调函数的参数来判断e.detail.authSetting。函数