728x90
반응형
HTML에서 자체적으로 제공하는 Geolocation API로 현재 사용자의 위치정보를 얻을 수 있다.
navigator object
브라우저에 대한 다양한 정보를 제공하는 객체이다.
이navigator 객체를 이용해 geolocation 정보를 통해 위치정보를 얻을 수 있다.
gelocation.getCurrentPosition 의 callback 함수를 통해, position 정보를 얻을 수 있다.
navigator.geolocation.getCurrentPosition(success, error, [options])
예시
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
Geolocation React Hook
이를 활용한 react hook 라이브러리도 존재한다.
굳이 라이브러리가 아니더라도, hook을 직접 구현해서 사용할 수도 있다.
코드출처: https://velog.io/@nemo/react-geolocation-api-hook
import { useState, useEffect } from 'react';
interface locationType {
loaded: boolean;
coordinates?: { lat: number; lng: number };
error?: { code: number; message: string };
}
const useGeolocation = () => {
const [location, setLocation] = useState<locationType>({
loaded: false,
coordinates: { lat: 0, lng: 0, }
})
// 성공에 대한 로직
const onSuccess = (location: { coords: { latitude: number; longitude: number; }; }) => {
setLocation({
loaded: true,
coordinates: {
lat: location.coords.latitude,
lng: location.coords.longitude,
}
})
}
// 에러에 대한 로직
const onError = (error: { code: number; message: string; }) => {
setLocation({
loaded: true,
error,
})
}
useEffect(() => {
// navigator 객체 안에 geolocation이 없다면
// 위치 정보가 없는 것.
if (!("geolocation" in navigator)) {
onError({
code: 0,
message: "Geolocation not supported",
})
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}, [])
return location;
}
export default useGeolocation
728x90
반응형
'🌳Frontend > react' 카테고리의 다른 글
ReactNode vs JSX.Element vs ReactElement (0) | 2023.06.15 |
---|---|
React 에서의 선언적 프로그래밍 (0) | 2023.06.07 |
[Next.js] SSR, SSG, Network (0) | 2023.05.28 |
Next.js 에서 SVG 파일을 import 해오는 방법 (0) | 2023.05.28 |
[TDD] 투두리스트를 TDD로 개발하기 - TodoForm (0) | 2023.05.25 |