반응형
    
    
    
  소개
사용자의 위치 정보인 좌표 위도, 경도 값이 필요할 때(지도 api, 현재 위치 날씨 등)가 있는데 그때 사용하는 기능을 소개합니다.
준비
https 도메인이 필요합니다 (developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only?hl=ko)
대부분의 브라우저에서 지원을 합니다

코드
시작시 위치 정보를 가져오는 코드
window.onload = function() {
  var startPos;
  var geoSuccess = function(position) {
    startPos = position;
    document.getElementById('startLat').innerHTML = startPos.coords.latitude;
    document.getElementById('startLon').innerHTML = startPos.coords.longitude;
  };
  navigator.geolocation.getCurrentPosition(geoSuccess);
};
예제 코드
<!doctype html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<div id="startLat"></div>
<div id="startLon"></div>
<script>
    (function() {
        window.onload = function() {
            var startPos;
            var geoSuccess = function(position) {
                startPos = position;
                document.getElementById('startLat').innerHTML = startPos.coords.latitude;
                document.getElementById('startLon').innerHTML = startPos.coords.longitude;
            };
            navigator.geolocation.getCurrentPosition(geoSuccess);
        };
    })();
</script>
</body>
</html>
예제 코드 확인
wizd100.github.io/example/geolocation
권한을 허용해야만 위도, 경도 값을 가져올 수 있습니다.

사이트에 접속하자 마자 위치 정보 권한을 요구를 하면 거부감을 갖게 됨으로
버튼을 클릭하여 위치 정보를 가져오는 코드
if('geolocation' in navigator) {
    /* 위치정보 사용 가능 */
} else {
    /* 위치정보 사용 불가능 */
}
const currentGeoLocation = document.getElementById("currentGeoLocation");
currentGeoLocation.onclick = function() {
    var startPos;
    var geoOptions = {
        timeout: 10 * 1000
    };
    var element = document.getElementById("nudge");
    var showNudgeBanner = function () {
        nudge.style.display = "block";
    };
    var hideNudgeBanner = function () {
        nudge.style.display = "none";
    };
    var nudgeTimeoutId = setTimeout(showNudgeBanner, 5000);
    var geoSuccess = function (position) {
        hideNudgeBanner();
        // We have the location, don't display banner
        clearTimeout(nudgeTimeoutId);
        // Do magic with location
        startPos = position;
        document.getElementById('startLat').innerHTML = startPos.coords.latitude;
        document.getElementById('startLon').innerHTML = startPos.coords.longitude;
    };
    var geoError = function (error) {
        console.log('Error occurred. Error code: ' + error.code);
        // error.code can be:
        //   0: unknown error
        //   1: permission denied
        //   2: position unavailable (error response from location provider)
        //   3: timed out
        switch (error.code) {
            case error.PERMISSION_DENIED:
                // The user didn't accept the callout
                document.getElementById('nudge').innerHTML = '위치정보 허용 권한이 없습니다';
                showNudgeBanner();
                break;
            case error.POSITION_UNAVAILABLE:
                // The user didn't accept the callout
                document.getElementById('nudge').innerHTML = '위치 정보를 가져오지 못했습니다';
                showNudgeBanner();
                break;
            case error.TIMEOUT:
                // The user didn't accept the callout
                document.getElementById('nudge').innerHTML = '시간 초과';
                showNudgeBanner();
                break;
        };
    };
    navigator.geolocation.getCurrentPosition(geoSuccess, geoError, geoOptions);
};
예제 코드2
<!doctype html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<button id="currentGeoLocation">좌표 가져오기</button>
<div id="nudge"></div>
<div id="startLat"></div>
<div id="startLon"></div>
<script>
    (function() {
        if('geolocation' in navigator) {
            /* 위치정보 사용 가능 */
        } else {
            /* 위치정보 사용 불가능 */
        }
        const currentGeoLocation = document.getElementById("currentGeoLocation");
        currentGeoLocation.onclick = function() {
            var startPos;
            var geoOptions = {
                timeout: 10 * 1000
            };
            var element = document.getElementById("nudge");
            var showNudgeBanner = function () {
                nudge.style.display = "block";
            };
            var hideNudgeBanner = function () {
                nudge.style.display = "none";
            };
            var nudgeTimeoutId = setTimeout(showNudgeBanner, 5000);
            var geoSuccess = function (position) {
                hideNudgeBanner();
                // We have the location, don't display banner
                clearTimeout(nudgeTimeoutId);
                // Do magic with location
                startPos = position;
                document.getElementById('startLat').innerHTML = startPos.coords.latitude;
                document.getElementById('startLon').innerHTML = startPos.coords.longitude;
            };
            var geoError = function (error) {
                console.log('Error occurred. Error code: ' + error.code);
                // error.code can be:
                //   0: unknown error
                //   1: permission denied
                //   2: position unavailable (error response from location provider)
                //   3: timed out
                switch (error.code) {
                    case error.PERMISSION_DENIED:
                        // The user didn't accept the callout
                        document.getElementById('nudge').innerHTML = '위치정보 허용 권한이 없습니다';
                        showNudgeBanner();
                        break;
                    case error.POSITION_UNAVAILABLE:
                        // The user didn't accept the callout
                        document.getElementById('nudge').innerHTML = '위치 정보를 가져오지 못했습니다';
                        showNudgeBanner();
                        break;
                    case error.TIMEOUT:
                        // The user didn't accept the callout
                        document.getElementById('nudge').innerHTML = '시간 초과';
                        showNudgeBanner();
                        break;
                };
            };
            navigator.geolocation.getCurrentPosition(geoSuccess, geoError, geoOptions);
        };
    })();
</script>
</body>
</html>예제 코드2 확인
wizd100.github.io/example/geolocation2
참고 사이트
developer.mozilla.org/ko/docs/Web/API/Navigator/geolocation
developers.google.com/web/fundamentals/native-hardware/user-location?hl=ko
반응형
    
    
    
  '언어 > javascript' 카테고리의 다른 글
| 자바스크립트 브라우저 사이즈 변경시 가로, 세로 길이 값 가져오는 기능 (2) | 2020.12.22 | 
|---|
댓글