Geolocation API - 위치 정보 받아오기
Post

Geolocation API - 위치 정보 받아오기

배운 것

Geolocation API

기능

  • 브라우저에서 위도와 경도 값을 받아오는 기능을 함.

geolocation 객체

  • navigator.geolocation 객체를 통해 Geolocation API를 사용할 수 있음.

사용 방법

  • geolocation 객체가 존재하는 지 확인
if('geolocation' in navigator) {
  /* 위치정보 사용 가능 */
} else {
  /* 위치정보 사용 불가능 */
}
  • 현재 위치 가져오기

    • getCurrentPosition() 메서드를 호출해서 현재 위치를 받아올 수 있다.
    navigator.geolocation.getCurrentPosition((position) => {
    doSomething(position.coords.latitude, position.coords.longitude);
      });
    
    • 참고로 첫 번째 매개변수로 넣은 콜백함수에서 위치를 받아오는데 두 번째 매개변수에 콜백함수를 넣으면
    • 값을 받아오는 것이 실패했을 때 실행될 코드를 작성할 수 있다.
      navigator.geolocation.getCurrentPosition((position) => {
    doSomething(position.coords.latitude, position.coords.longitude);
      }, () => {
          console.log('실패했어 ㅠㅠ')
      });
    
  • 현재 위치 추적하기

    • watchPosition() 메서드로 바뀐 위치 정보를 호출할 수 있다.
      const watchID = navigator.geolocation.watchPosition((position) => {
      doSomething(position.coords.latitude, position.coords.longitude);
      });
      

Reference