Skip to content

Commit

Permalink
✨ feat: 현재 위치 기준 지도 설정 기능 구현 #5
Browse files Browse the repository at this point in the history
  • Loading branch information
MrMirror21 committed Oct 19, 2024
1 parent 09994cd commit 826054b
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/api/map.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { GeoApiResponse, GeoPosition } from '@/types/api/map';
import { apiKaKao } from '.';
import { Dispatch, SetStateAction } from 'react';

export const getGeoInfo = (
setCurrentPosition: Dispatch<SetStateAction<GeoPosition>>,
): Promise<GeoApiResponse> => {
return new Promise((resolve, reject) => {
if (!navigator.geolocation) {
reject(new Error('Geolocation is not supported by this browser.'));
} else {
navigator.geolocation.getCurrentPosition(
async (position) => {
setCurrentPosition({
lat: position.coords.latitude,
lon: position.coords.longitude,
});
try {
const response = await apiKaKao.get(
`geo/coord2regioncode.json?x=${position.coords.longitude}&y=${position.coords.latitude}`,
);
if (response.data.documents && response.data.documents.length > 0) {
resolve(response.data.documents[0]);
} else {
reject(new Error('No location data found'));
}
} catch (error) {
reject(error);
}
},
(error) => {
reject(new Error(`Geolocation error: ${error.message}`));
}
);
}
});
};
13 changes: 13 additions & 0 deletions src/hooks/api/useKaKaoMap.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { getGeoInfo } from '@/api/map';
import { GeoPosition } from '@/types/api/map';
import { useQuery } from '@tanstack/react-query';
import { Dispatch, SetStateAction } from 'react';

export function useGetGeoInfo(
setCurrentPosition: Dispatch<SetStateAction<GeoPosition>>,
) {
return useQuery({
queryKey: ['event'],
queryFn: () => getGeoInfo(setCurrentPosition),
});
}

0 comments on commit 826054b

Please sign in to comment.