From 78ad55316f9f355d1a94d5de0d40d16406a6e4db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=87=AF=E6=A5=A0?= <1403191743@qq.com> Date: Fri, 6 Jun 2025 02:24:31 +0000 Subject: [PATCH] update static/js/CommonFunction.js. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 陈凯楠 <1403191743@qq.com> --- static/js/CommonFunction.js | 75 ++++++++++++++++++++++++++++++++----- 1 file changed, 65 insertions(+), 10 deletions(-) diff --git a/static/js/CommonFunction.js b/static/js/CommonFunction.js index cde3d8a..9443de2 100644 --- a/static/js/CommonFunction.js +++ b/static/js/CommonFunction.js @@ -95,18 +95,73 @@ Vue.prototype.showImg = img => { } // 获取经纬度 -Vue.prototype.getLocation = () => { - uni.startLocationUpdate({ - success: res => { - uni.onLocationChange(data => { - uni.setStorageSync('location', { - lat: data.latitude, - lon: data.longitude +Vue.prototype.getLocation = function(callback) { + // 检查权限状态 + uni.getSetting({ + success: (res) => { + if (res.authSetting['scope.userLocation'] === false) { + // 已拒绝权限,引导用户去设置 + uni.showModal({ + title: '权限申请', + content: '需要位置权限才能获取当前城市', + confirmText: '去设置', + success: (res) => { + if (res.confirm) { + uni.openSetting(); + } else { + callback && callback(null, { + errMsg: '用户拒绝授权' + }); + } + } }); - }) + } else { + // 未授权或已授权,请求位置 + this._requestLocation(callback); + } + }, + fail: (err) => { + console.error('获取权限状态失败:', err); + callback && callback(null, err); } - }) -} + }); +}; + +// 私有方法:请求位置 +Vue.prototype._requestLocation = function(callback) { + // 直接获取位置(微信小程序不需要先调用startLocationUpdate) + uni.getLocation({ + type: 'wgs84', // 坐标系类型 + success: (res) => { + console.log('获取位置成功:', res); + const location = { + lat: res.latitude, + lon: res.longitude + }; + uni.setStorageSync('location', location); + callback && callback(location); + }, + fail: (err) => { + console.error('获取位置失败:', err); + + if (err.errMsg.includes('auth deny')) { + // 权限被拒绝,引导用户去设置 + uni.showModal({ + title: '权限申请', + content: '需要位置权限才能获取当前城市', + confirmText: '去设置', + success: (res) => { + if (res.confirm) { + uni.openSetting(); + } + } + }); + } + + callback && callback(null, err); + } + }); +}; // 路由页面跳转 Vue.prototype.gotoPath = path => {