본문 바로가기

study/Front

Geolocation API로 실시간 위치 정보 가져오기

Geolocation API로 실시간 위치 정보 가져오기

2024. 9. 8. 18:58· JavaScript

https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API

 

Geolocation API - Web APIs | MDN

The Geolocation API allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked for permission to report location information.

developer.mozilla.org

1. Geolocation API란?

Geolocation API는 웹사이트가 사용자의 기기에서 위치 정보를 요청할 수 있도록 해주는 기능입니다.

위치 정보는 사용자의 허락을 받아야만 가져올 수 있습니다.

2. 위치 정보 가져오기: getCurrentPosition()

위치 정보를 한 번만 가져오려면 getCurrentPosition() 메서드를 사용합니다.

이 메서드는 성공 시 실행될 함수(필수), 실패 시 실행될 함수(필수), 그리고 추가 설정 옵션(선택)을 인수로 받습니다.

JAVASCRIPT

 

navigator.geolocation.getCurrentPosition(
    (position) => {
        console.log("위도: " + position.coords.latitude);
        console.log("경도: " + position.coords.longitude);
    },
    (error) => {
        console.error("오류 발생: ", error);
    }
);

3. 위치 정보 객체 (position) 자세히 알아보기

성공적으로 위치 정보를 가져오면 position 객체가 반환됩니다.

이 객체에는 사용자 기기의 여러 위치 정보가 들어 있습니다.

  • coords.latitude: 위도 (ex: 37.5172)
  • coords.longitude: 경도 (ex: 127.0473)
  • coords.altitude: 고도, 미터 단위 (사용할 수 없으면 null).
  • coords.accuracy: 위치의 정확도, 미터 단위.
  • coords.altitudeAccuracy: 고도의 정확도 (사용할 수 없으면 null).
  • coords.heading: 기기가 가리키고 있는 방향 (정지 상태일 경우 null).
  • coords.speed: 기기의 이동 속도, m/s 단위 (정지 상태일 경우 null)
JAVASCRIPT

 

navigator.geolocation.getCurrentPosition(
    (position) => {
        const { latitude, longitude, accuracy, altitude, heading, speed } = position.coords;
        console.log(`위도: ${latitude}, 경도: ${longitude}`);
        console.log(`정확도: ${accuracy}m`);
        console.log(`고도: ${altitude !== null ? altitude + "m" : "정보 없음"}`);
        console.log(`방향: ${heading !== null ? heading + "°" : "정지 상태"}`);
        console.log(`속도: ${speed !== null ? speed + "m/s" : "정지 상태"}`);
    }
);

4. 오류 처리

위치 정보를 가져오는 중 발생하는 오류는 크게 세 가지로 나눌 수 있습니다.

  • PERMISSION_DENIED: 사용자가 위치 정보 접근을 거부한 경우.
  • POSITION_UNAVAILABLE: 기기의 위치 정보를 사용할 수 없는 경우.
  • TIMEOUT: 위치 정보를 가져오는 시간이 초과된 경우.
JAVASCRIPT

 

navigator.geolocation.getCurrentPosition(
    (position) => {
        // 위치 정보를 성공적으로 가져옴
    },
    (error) => {
        switch (error.code) {
            case error.PERMISSION_DENIED:
                alert("위치 정보 접근이 거부되었습니다.");
                break;
            case error.POSITION_UNAVAILABLE:
                alert("위치 정보를 사용할 수 없습니다.");
                break;
            case error.TIMEOUT:
                alert("위치 정보를 가져오는 데 시간이 너무 오래 걸렸습니다.");
                break;
            default:
                alert("알 수 없는 오류가 발생했습니다.");
        }
    }
);

5. 위치 요청 시 옵션 설정하기

getCurrentPosition() 메서드는 추가적인 옵션을 설정할 수 있습니다.

  • enableHighAccuracy: 위치 정보의 정확도를 높일지 여부(기본값 false)
    true로 설정하면 더 정확한 위치 정보를 제공하지만, 배터리 소모량이 증가할 수 있습니다.
  • timeout: 위치 정보를 가져오는 데 걸리는 최대 시간 (밀리초 단위).
  • maximumAge: 이전 위치 정보를 얼마 동안 캐시할지 (밀리초 단위). 0으로 설정 시 항상 최신 정보를 요청합니다.
JAVASCRIPT

 

navigator.geolocation.getCurrentPosition(
    (position) => {
        console.log(`위도: ${position.coords.latitude}, 경도: ${position.coords.longitude}`);
    },
    (error) => {
        console.error("위치 정보를 가져오는 중 오류 발생: ", error);
    },
    {
        enableHighAccuracy: true,  // 고정밀도 위치 요청
        timeout: 5000,             // 5초 이내에 위치 정보를 가져오지 않으면 오류 처리
        maximumAge: 0              // 캐시된 위치 정보 사용 안 함
    }
);

 

https://hy-un.tistory.com/entry/Geolocation-API%EB%A1%9C-%EC%8B%A4%EC%8B%9C%EA%B0%84-%EC%9C%84%EC%B9%98-%EC%A0%95%EB%B3%B4-%EA%B0%80%EC%A0%B8%EC%98%A4%EA%B8%B0