방법: 사용자의 위치 가져오기

게시일 24. 1월 2023 작성자 Jan Bunk


저희 앱은 더 많은 개발 기능과 앱 사용자에게 최적화된 경험을 제공하기 위해 navigator.geolocation JavaScript API를 수정해요.

이 페이지에 설명된 제한 사항에 유의하면 위치 정보 JavaScript 함수를 평소처럼 사용할 수 있어요.

추가 함수

openAppLocationSettings

이 함수는 Android에서는 앱 정보 화면을, iOS에서는 설정 앱을 열어요. 사용자는 이전에 권한 요청을 거부했더라도 여기에서 앱의 위치 접근 권한을 활성화할 수 있어요.

아래의 오류 처리 섹션에서 코드 예시와 함께 이 함수를 호출하면 유용한 경우를 확인할 수 있어요.

appResumed 이벤트를 수신하여 사용자가 설정에서 돌아온 시점을 감지할 수 있어요.

openDeviceLocationSettings

이 함수는 사용자가 위치 서비스를 활성화할 수 있는 Android 설정 앱을 열어요. iOS에서도 설정 앱을 열지만, 기술적 제한으로 인해 위치 서비스를 관리하는 정확한 페이지를 열지는 못해요.

아래의 오류 처리 섹션에서 코드 예시와 함께 이 함수를 호출하면 유용한 경우를 확인할 수 있어요.

appResumed 이벤트를 수신하여 사용자가 설정에서 돌아온 시점을 감지할 수 있어요.

오류 처리

현재 위치를 가져올 때 발생할 수 있는 오류의 원인은 여러 가지예요. 기존 위치 정보 API와의 호환성을 유지하면서 정확히 무엇이 잘못되었는지에 관한 추가 정보도 제공해요.


function getAppErrorMessage(error) {
    if (error.hasOwnProperty("appMessage")) {
        return error.appMessage;
    }
    else {
        return null;
    }
}

var options = {
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 0
};

navigator.geolocation.getCurrentPosition(function(position) {
    // success
    console.log("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
}, async function(error) {
    // error
    switch(error.code) {
        case error.PERMISSION_DENIED:
            // error.message is always "User denied Geolocation" to be consistent with browser behaviour
            console.log("User denied Geolocation");

            // Additional information only available for app users:
            if (getAppErrorMessage(error) === "Permission denied") {
                console.log("User did not grant the app permission to access the location, but we can try again later.");
            }
            else if (getAppErrorMessage(error) === "Permission denied permanently") {
                console.log("User did not grant the app permission to access the location and can only enable the permissions via the app settings.");

                // You can open the app settings like this:
                await openAppLocationSettings();
            }
            else if (getAppErrorMessage(error) === "Location service disabled") {
                console.log("User did not enable the location service setting in the device settings, even after being prompted to do so by the app.");

                // You can open the device's location settings like this:
                await openDeviceLocationSettings();
            }

            break;
        case error.POSITION_UNAVAILABLE:
            // can occurr in browsers with message "Unknown error acquiring position", but not used by the app at the moment
            console.log("Unknown error acquiring position");
            break;
        case error.TIMEOUT:
            // error.message is always "Position acquisition timed out" to be consistent with browser behaviour
            console.log("The request to get user location took longer than " + options.timeout + " milliseconds.");
            break;
    }

}, options);
    

제한 사항

  • navigator.geolocation.getCurrentPosition을 호출하면 GeolocationCoordinates 또는 GeolocationPositionError 객체가 반환되는 것이 아니므로 해당 타입을 확인하지 마세요. 하지만 예상되는 모든 속성에는 계속 접근할 수 있어요.
  • GeolocationCoordinates.altitudeAccuracy와 같은 일부 속성을 기기에서 지원하지 않는 경우 브라우저는 일반적으로 null을 반환하지만, 저희는 기기에서 받은 값에 따라 0을 반환할 수 있어요.