자바스크립트 현재 위치 가져오기

J·2023년 10월 5일
0

al-ways

목록 보기
5/8

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 };
};
profile
벨로그로 이사 중

0개의 댓글