import { defineStore } from 'pinia'; import { ref } from 'vue' import { msg } from '@/common/globalFunction.js' import config from '../config'; const defalutLongLat = { longitude: 120.382665, latitude: 36.066938, } const useLocationStore = defineStore("location", () => { // 定义状态 const longitudeVal = ref(null) // 经度 const latitudeVal = ref(null) //纬度 const timer = ref(null) const count = ref(0) function getLocation() { // 获取经纬度两个平台 return new Promise((resole, reject) => { try { if (lightAppJssdk.map) { lightAppJssdk.map.getLocation({ success: function(data) { longitudeVal.value = Number(data.longitude) latitudeVal.value = Number(data.latitude) resole(data) }, fail: function(data) { longitudeVal.value = defalutLongLat.longitude latitudeVal.value = defalutLongLat.latitude resole(defalutLongLat) msg('用户位置获取失败') console.log('失败3', data) } }) } else { uni.getLocation({ type: 'gcj02', // highAccuracyExpireTime: 3000, // isHighAccuracy: true, // timeout: 2000, success: function(data) { longitudeVal.value = Number(data.longitude) latitudeVal.value = Number(data.latitude) resole(data) }, fail: function(data) { longitudeVal.value = defalutLongLat.longitude latitudeVal.value = defalutLongLat.latitude resole(defalutLongLat) msg('用户位置获取失败') console.log('失败2', data) } }); } } catch (e) { longitudeVal.value = defalutLongLat.longitude latitudeVal.value = defalutLongLat.latitude resole(defalutLongLat) msg('测试环境,使用模拟定位') console.log('失败1', e) } }) } function getLocationLoop(gap = 1000 * 60 * 2) { console.log(`🔄开始循环获取定位,间隔:${Math.floor(gap/1000)}秒`) const run = () => { count.value++ console.log(`📍第${count.value}次获取定位`) getLocation() } run() timer.value = setInterval(run,gap); } function clearGetLocationLoop(params) { clearInterval(timer.value) timer.value = null } function longitude() { return longitudeVal.value } function latitude() { return latitudeVal.value } // 导入 return { getLocation, getLocationLoop, clearGetLocationLoop, longitudeVal, latitudeVal, } }, { unistorage: true, }) export default useLocationStore;