import { defineStore } from 'pinia' import locationUtil from '@/utils/location.js' import { reportLocationApi } from '@/api/map.js' const useLocationStore = defineStore('location', { state: () => ({ // 当前位置信息 currentLocation: null, // 位置权限状态 hasPermission: false, // 系统定位服务是否开启 systemLocationEnabled: true, // 位置更新间隔(毫秒) updateInterval: 5000, // 位置监听器ID watcherId: null, // 上次位置上报时间 lastReportTime: 0 }), getters: { /** * 获取当前位置 * @returns {Object|null} 当前位置信息 */ getCurrentLocation: (state) => state.currentLocation, /** * 获取位置权限状态 * @returns {boolean} 是否有位置权限 */ getPermissionStatus: (state) => state.hasPermission, /** * 获取系统定位服务状态 * @returns {boolean} 系统定位服务是否开启 */ getSystemLocationStatus: (state) => state.systemLocationEnabled }, actions: { /** * 初始化位置服务 */ async initLocationService() { try { // 检查系统定位服务是否开启 this.systemLocationEnabled = await locationUtil.checkSystemLocationEnabled(); if (!this.systemLocationEnabled) { console.warn('系统定位服务未开启'); } // 请求位置权限 this.hasPermission = await locationUtil.requestLocationPermission(); if (this.hasPermission) { // 获取当前位置 await this.updateCurrentLocation(); // 开始位置监听 this.startLocationWatch(); } } catch (error) { console.error('初始化位置服务失败:', error); } }, /** * 更新当前位置 */ async updateCurrentLocation() { try { const location = await locationUtil.getCurrentLocation(); this.currentLocation = location; console.log('位置更新:', location); return location; } catch (error) { console.error('更新位置失败:', error); return null; } }, /** * 开始位置监听 */ startLocationWatch() { if (this.watcherId) { this.stopLocationWatch(); } this.watcherId = locationUtil.startLocationWatcher((location) => { this.currentLocation = location; // 可以在这里添加位置信息上报逻辑 this.reportLocation(location); }, { interval: this.updateInterval }); }, /** * 停止位置监听 */ stopLocationWatch() { if (this.watcherId) { locationUtil.stopLocationWatcher(); this.watcherId = null; } }, /** * 重新请求位置权限 */ async reRequestPermission() { this.hasPermission = await locationUtil.requestLocationPermission(); if (this.hasPermission) { await this.updateCurrentLocation(); this.startLocationWatch(); } return this.hasPermission; }, /** * 位置信息上报 * @param {Object} location 位置信息 */ async reportLocation(location) { try { const now = Date.now(); // 检查是否达到上报时间间隔(1分钟) if (now - this.lastReportTime >= 60000) { // 构造请求参数 const params = { longitude: location.longitude, latitude: location.latitude, // reportTime: new Date().toISOString() }; // 调用位置上报接口 const result = await reportLocationApi(params); console.log('位置上报成功:', result); // 更新上次上报时间 this.lastReportTime = now; } } catch (error) { console.error('位置上报失败:', error); } }, /** * 清理位置服务 */ cleanupLocationService() { this.stopLocationWatch(); this.currentLocation = null; } } }) export default useLocationStore