navigator.geolocation.getCurrentPosition() API를 사용해 유저의 현재 위치를 얻을 수 있다.
getCurrentPosition() 함수가 성공적으로 정보를 가져오면 coords, timestamp 등의 정보를 담은 객체를 반환하는데, coords 속성 내에서 latitude(위도)와 longitude(경도)를 사용할 수 있다.
JS로 현재 위치 가져오는 커스텀 훅
// useCurrentLocation.ts
import { useState, useEffect } from 'react';
export const useCurrentLocation = () => {
const [coords, setCoords] = useState<CoordsData | null>(null);
const getLocation = () => {
navigator.geolocation.getCurrentPosition((position) => {
let lat = position.coords.latitude;
let lon = position.coords.longitude;
setCoords({ lat, lon });
});
};
useEffect(() => {
getLocation();
}, []);
return { coords };
};