微信小程序獲取地理位置受權,首先須要在app.json中添加配置:git
"permission": { "scope.userLocation": { "desc": "請確認受權" } }
獲取經緯度:若是手機未開啓位置信息,那麼受權成功後在wx.getLocation()方法中也會一直失敗,因此須要在fail方法中提示用戶開啓手機位置信息json
getUserLocation: function () { let vm = this wx.getSetting({ success: (res) => { // res.authSetting['scope.userLocation'] == undefined 表示 初始化進入該頁面 // res.authSetting['scope.userLocation'] == false 表示 非初始化進入該頁面,且未受權 // res.authSetting['scope.userLocation'] == true 表示 地理位置受權 // 拒絕受權後再次進入從新受權 if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) { // console.log('authSetting:status:拒絕受權後再次進入從新受權', res.authSetting['scope.userLocation']) wx.showModal({ title: '', content: '【泰福利Lite】須要獲取你的地理位置,請確認受權', success: function (res) { if (res.cancel) { wx.showToast({ title: '拒絕受權', icon: 'none' }) setTimeout(() => { wx.navigateBack() }, 1500) } else if (res.confirm) { wx.openSetting({ success: function (dataAu) { // console.log('dataAu:success', dataAu) if (dataAu.authSetting["scope.userLocation"] == true) { //再次受權,調用wx.getLocation的API vm.getLocation(dataAu) } else { wx.showToast({ title: '受權失敗', icon: 'none' }) setTimeout(() => { wx.navigateBack() }, 1500) } } }) } } }) } // 初始化進入,未受權 else if (res.authSetting['scope.userLocation'] == undefined) { // console.log('authSetting:status:初始化進入,未受權', res.authSetting['scope.userLocation']) //調用wx.getLocation的API vm.getLocation(res) } // 已受權 else if (res.authSetting['scope.userLocation']) { // console.log('authSetting:status:已受權', res.authSetting['scope.userLocation']) //調用wx.getLocation的API vm.getLocation(res) } } }) }, // 微信得到經緯度 getLocation: function (userLocation) { let vm = this wx.getLocation({ type: "wgs84", success: function (res) { // console.log('getLocation:success', res) var latitude = res.latitude var longitude = res.longitude vm.getDaiShu(latitude, longitude) }, fail: function (res) { // console.log('getLocation:fail', res) if (res.errMsg === 'getLocation:fail:auth denied') { wx.showToast({ title: '拒絕受權', icon: 'none' }) setTimeout(() => { wx.navigateBack() }, 1500) return } if (!userLocation || !userLocation.authSetting['scope.userLocation']) { vm.getUserLocation() } else if (userLocation.authSetting['scope.userLocation']) { wx.showModal({ title: '', content: '請在系統設置中打開定位服務', showCancel: false, success: result => { if (result.confirm) { wx.navigateBack() } } }) } else { wx.showToast({ title: '受權失敗', icon: 'none' }) setTimeout(() => { wx.navigateBack() }, 1500) } } }) }