GetCurrentLocation.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import LightVillageApi from "@/api/light/LightVillageApi";
  2. import MapApi from "@/api/map/MapApi";
  3. import TenMapApi from "@/api/map/TenMapApi";
  4. import { useVillageStore } from "@/store/village";
  5. import { ref } from "vue";
  6. export function useGetCurrentLocation(
  7. options: {
  8. onCityChanged?: (city: string) => void;
  9. }
  10. ) {
  11. const { onCityChanged } = options;
  12. const villageStore = useVillageStore();
  13. const currentLonlat = ref<{ longitude: number, latitude: number }>({
  14. longitude: 0,
  15. latitude: 0,
  16. });
  17. async function getCurrentExactLocation() {
  18. return new Promise((resolve, reject) => {
  19. uni.getLocation({
  20. type: 'wgs84',
  21. success: async (res) => {
  22. currentLonlat.value = {
  23. longitude: res.longitude,
  24. latitude: res.latitude,
  25. };
  26. villageStore.setCurrentLonlat(currentLonlat.value);
  27. const address = (await TenMapApi.geocoder(`${res.latitude},${res.longitude}`));
  28. villageStore.setCurrentRegion(address?.address_component?.city || '');
  29. onCityChanged?.(address?.address_component?.city || '');
  30. resolve(currentLonlat.value);
  31. },
  32. fail: (err) => {
  33. reject(err);
  34. },
  35. });
  36. });
  37. }
  38. async function getCurrentFuzzyLocation() {
  39. const res = await LightVillageApi.getIpAddress();
  40. currentLonlat.value = {
  41. longitude: Number(res.point.x),
  42. latitude: Number(res.point.y),
  43. };
  44. villageStore.setCurrentLonlat(currentLonlat.value);
  45. villageStore.setCurrentRegion(res.address_detail.district);
  46. onCityChanged?.(res.address_detail.city);
  47. }
  48. async function setCurrentLocationWithCity(city: string) {
  49. const res = (await MapApi.simpleGetRegion(city)).requireData();
  50. currentLonlat.value = {
  51. longitude: Number(res.center.split(',')[0]),
  52. latitude: Number(res.center.split(',')[1]),
  53. };
  54. console.log('currentLonlat.value', currentLonlat.value);
  55. villageStore.setCurrentLonlat(currentLonlat.value);
  56. villageStore.setCurrentRegion(res.name);
  57. onCityChanged?.(city);
  58. }
  59. return {
  60. currentLonlat,
  61. getCurrentExactLocation,
  62. getCurrentFuzzyLocation,
  63. setCurrentLocationWithCity,
  64. };
  65. }