diff --git a/stores/user.js b/stores/user.js index 6ce623f..82e7c31 100644 --- a/stores/user.js +++ b/stores/user.js @@ -182,7 +182,15 @@ export const productStore = defineStore("product", { await this.actionsproductqueryShop(); } } - const canOrder = await this.computedDistance(); + + if (this.shopInfo.isOrderFence == 0) { + this.jumpToOrderPage(); + return; + } + const canGetLocation = await this.openLocationAuth(); + if (canGetLocation) { + const canOrder = await this.computedDistance(); + } } } else { // #ifdef APP || MP-WEIXIN || MP-ALIPAY @@ -211,7 +219,14 @@ export const productStore = defineStore("product", { await this.actionsproductqueryShop(); } } - const canOrder = await this.computedDistance(); + if (this.shopInfo.isOrderFence == 0) { + this.jumpToOrderPage(); + return; + } + const canGetLocation = await this.openLocationAuth(); + if (canGetLocation) { + const canOrder = await this.computedDistance(); + } } }, fail: (res) => { @@ -222,7 +237,64 @@ export const productStore = defineStore("product", { } }); }, - + async openLocationAuth() { + try { + // 1. 检查当前位置授权状态 + return new Promise((resolve, reject) => { + uni.getSetting({ + success: (settingRes) => { + if (settingRes.authSetting["scope.userLocation"]) { + // 2. 已授权:直接获取位置 + resolve(true); + } else if ( + settingRes.authSetting["scope.userLocation"] === undefined + ) { + // 3. 未请求过授权:发起授权请求 + uni + .authorize({ scope: "scope.userLocation" }) + .then((authRes) => { + if (authRes.errMsg === "authorize:ok") { + // 授权成功后获取位置 + resolve(true); + } else { + reject(false); + } + }); + } else { + // 4. 已拒绝授权:提示用户去设置页开启 + uni.showModal({ + title: "开启定位", + content: "请允许“零点八零”使用您的位置,方便您进入店铺点餐", + confirmText: "开启定位", + cancelText: "取消", + success: (modalRes) => { + if (modalRes.confirm) { + // 跳转微信小程序授权设置页 + uni.openSetting({ + success: async (openRes) => { + // 用户在设置页开启授权后,再次获取位置 + if (openRes.authSetting["scope.userLocation"]) { + resolve(true); + } else { + reject(false); + } + }, + }); + } + }, + }); + } + }, + fail: (err) => { + reject(err); + }, + }); + }); + } catch (err) { + console.error("位置授权失败:", err); + uni.showToast({ title: "授权失败,请稍后重试", icon: "none" }); + } + }, //计算距离判断是否可以点餐 async computedDistance() { return new Promise((resolve, reject) => { @@ -233,11 +305,6 @@ export const productStore = defineStore("product", { this.location.longitude ); - if (this.shopInfo.isOrderFence == 0) { - this.jumpToOrderPage(); - resolve(true); - return; - } const juli = getDistance( this.location.latitude, this.location.longitude, @@ -256,7 +323,7 @@ export const productStore = defineStore("product", { confirmText: "重新定位", content: "抱歉,您当前距离店铺过远,为保障您的用餐体验,请您到店后或在门店附近再下单。若您已在店铺附近,可尝试重新定位", - success: async(res) => { + success: async (res) => { if (res.confirm) { console.log("用户点击了确认"); await this.getLocation();