uniapp-微信小程式定位(授權定位)
阿新 • • 發佈:2021-12-13
/** * 授權&定位 */ export default { data() { return { isLocated: false // 是否定位成功 } }, methods: { /** * 獲取經緯度並觸發回撥函式 * @param {Function} successCb 獲取成功回撥 * @param {Function} authDenyCb 獲取失敗回撥 */ getLocation(successCb, authDenyCb) { const self = this uni.getLocation({ type: 'wgs84', // 預設gps 座標 altitude: false, // 是否返回高度 accuracy: 'best', // 精度值為20m success(res) { successCb && successCb(res) self.isLocated = true }, fail(err) { if ( err.errMsg === 'getLocation:fail 頻繁呼叫會增加電量損耗,可考慮使用 wx.onLocationChange 監聽地理位置變化' ) { uni.showToast({ title: '請勿頻繁定位', icon: 'none' }) } if (err.errMsg === 'getLocation:fail auth deny') { // 未授權 uni.showToast({ title: '無法定位,請重新獲取位置資訊', icon: 'none' }) authDenyCb && authDenyCb() self.isLocated = false } if (err.errMsg === 'getLocation:fail:ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF') { uni.showModal({ content: '請開啟手機定位服務', showCancel: false }) } } }) }, /** * 重新授權並呼叫定位方法 * @param {Function} successCb 授權成功回撥 * @param {Function} authDenyCb 授權失敗回撥 */ getAuthorize(successCb, authDenyCb) { uni.authorize({ scope: 'scope.userLocation', success: () => { this.getLocation(successCb, authDenyCb) }, fail: (err) => { err = err['errMsg'] uni .showModal({ content: '需要授權位置資訊', confirmText: '確認授權' }) .then((res) => { if (res[1]['confirm']) { uni.openSetting({ success: (res) => { if (res.authSetting['scope.userLocation']) { // 授權成功 uni.showToast({ title: '授權成功', icon: 'none' }) } else { // 未授權 uni.showToast({ title: '授權失敗', icon: 'none' }) } this.getLocation(successCb, authDenyCb) } }) } if (res[1]['cancel']) { // 取消授權 console.log('取消') this.getLocation(successCb, authDenyCb) } }) } }) }, } }