import { defineStore } from 'pinia'
|
import locationUtil from '@/utils/location.js'
|
|
const useLocationStore = defineStore('location', {
|
state: () => ({
|
// 当前位置信息
|
currentLocation: null,
|
// 位置权限状态
|
hasPermission: false,
|
// 系统定位服务是否开启
|
systemLocationEnabled: true,
|
// 位置更新间隔(毫秒)
|
updateInterval: 5000,
|
// 位置监听器ID
|
watcherId: null
|
}),
|
|
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 位置信息
|
*/
|
reportLocation(location) {
|
// 这里可以添加位置信息上报到服务器的逻辑
|
// 例如:api.uploadLocation(location)
|
// console.log('位置上报:', location);
|
},
|
|
/**
|
* 清理位置服务
|
*/
|
cleanupLocationService() {
|
this.stopLocationWatch();
|
this.currentLocation = null;
|
}
|
}
|
})
|
|
export default useLocationStore
|