import { defineStore } from 'pinia' interface addressState { Location: { /** * 纬度 */ latitude: number | null /** * 经度 */ longitude: number | null } name: string city: string } export const useAddressStore = defineStore('address', { state: (): addressState => ({ Location: { latitude: null, longitude: null, }, name: '请选择位置', city: '', }), actions: { // 获取地理位置的函数 getLocation() { uni.showLoading({ mask: true }) // 1. 检查当前授权状态 uni.getSetting({ success: (res) => { const locationAuth = res.authSetting['scope.userLocation'] // 2. 已授权 - 直接获取位置 if (locationAuth) { this.fetchActualLocation() uni.hideLoading() } // 3. 未授权 - 尝试请求授权 else { uni.authorize({ scope: 'scope.userLocation', success: () => this.fetchActualLocation(), fail: () => this.showAuthGuide(), // 用户拒绝,显示引导 complete: () => uni.hideLoading(), }) } }, }) }, // 实际获取位置的方法 fetchActualLocation() { uni.getLocation({ type: 'wgs84', isHighAccuracy: true, altitude: true, success: (res) => { console.log('位置获取成功', res) this.Location.latitude = res.latitude this.Location.longitude = res.longitude }, fail: (err) => { console.log(err, '获取位置失败') if (err.errMsg === 'getLocation:fail system permission denied') { useGlobalToast().show('手机定位权限未打开,请手动在设置里面打开定位') } else { useGlobalToast().show(`获取定位失败:${err.errMsg}`) } }, }) }, // 显示授权引导 showAuthGuide() { uni.showModal({ title: '需要位置权限', content: '请开启位置授权以使用完整功能', confirmText: '去设置', success: (res) => { if (res.confirm) { // 4. 用户点击确认后打开设置页 wx.openSetting({ success: (settingRes) => { // 5. 检查用户是否在设置页中开启了授权 if (settingRes.authSetting['scope.userLocation']) { this.fetchActualLocation() } else { console.log('用户仍未授权') } }, }) } }, }) }, getMapAddress() { uni.chooseLocation({ success: (res) => { console.log(res, '收获地址') this.Location.latitude = res.latitude this.Location.longitude = res.longitude this.name = res.name }, fail: (e) => { console.log('获取地址失败', e) }, }) }, }, })