SFH5/hooks/useLocation.js
2026-03-16 11:10:28 +08:00

54 lines
1.4 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { reactive } from "vue";
import { useMainStore } from "@/store/index";
export function useLocation() {
const { storeState, setLocation } = useMainStore();
const locationState = reactive({
showGetLocation: false,
latitude: 0,
longitude: 0
});
const getLocation = () => {
return new Promise((resolve) => {
// 1⃣ 优先使用 store 里的定位
if (storeState.location?.latitude && storeState.location?.longitude) {
locationState.latitude = storeState.location.latitude;
locationState.longitude = storeState.location.longitude;
resolve(true);
return;
}
// 2⃣ 本地已经有定位
if (locationState.latitude && locationState.longitude) {
resolve(true);
return;
}
// 3⃣ 没有定位才请求
SFUIP.getLocation().then(res => {
if (!res.success) {
resolve(false);
return;
}
const { latitude, longitude } = res.data || {};
if (latitude && longitude) {
locationState.latitude = latitude;
locationState.longitude = longitude;
locationState.showGetLocation = false;
setLocation({ latitude, longitude });
resolve(true);
} else {
resolve(false);
}
});
});
};
return { locationState, getLocation };
}