찾다
웹 프론트엔드H5 튜토리얼HTML5 가이드 (4) - Geolocation 사용에 대한 자세한 설명

오늘 배울 내용은 Geolocation을 활용하여 위치 확인 기능을 구현하는 것입니다. 다음 메소드를 제공하는 navigator.geolocation을 통해 Geolocation 객체를 가져올 수 있습니다.

getCurrentPosition(callback,errorCallback,options): 현재 위치 가져오기

watchPosition(callback,error,options) ): 현재 위치 모니터링을 시작합니다.

clearWatch(id): 현재 위치 모니터링을 중지합니다.

참고: 아래 예시에 사용된 브라우저는 크롬입니다. 다른 브라우저를 사용하는 경우 실행 결과가 예시에 표시된 결과와 일치한다고 보장할 수 없습니다.

 1. 현재 위치 가져오기

현재 위치를 가져오기 위해 getCurrentPosition 메서드를 사용합니다. 위치 정보는 직접 반환되지 않습니다. 결과 형태로 처리하려면 콜백 함수를 사용해야 합니다. 좌표를 가져오는 데 약간의 지연이 있을 수 있으며, 액세스 권한을 묻는 메시지가 표시됩니다. 다음 예를 살펴보겠습니다.

<!DOCTYPE HTML><html><head>
    <title>Example</title>
    <style>
        table{border-collapse: collapse;}
        th, td{padding: 4px;}
        th{text-align: right;}
    </style></head><body>
    <table border="1">
        <tr>
            <th>Longitude:</th>
            <td id="longitude">-</td>
            <th>Latitude:</th>
            <td id="latitude">-</td>
        </tr>
        <tr>
            <th>Altitude:</th>
            <td id="altitude">-</td>
            <th>Accuracy:</th>
            <td id="accuracy">-</td>
        </tr>
        <tr>
            <th>Altitude Accuracy:</th>
            <td id="altitudeAccuracy">-</td>
            <th>Heading:</th>
            <td id="heading">-</td>
        </tr>
        <tr>
            <th>Speed:</th>
            <td id="speed">-</td>
            <th>Time Stamp:</th>
            <td id="timestamp">-</td>
        </tr>
    </table>
    <script>
        navigator.geolocation.getCurrentPosition(displayPosition);        
        function displayPosition(pos) {            
        var properties = [&#39;longitude&#39;, &#39;latitude&#39;, &#39;altitude&#39;, &#39;accuracy&#39;, &#39;altitudeAccuracy&#39;, &#39;heading&#39;, &#39;speed&#39;];            
        for (var i = 0, len = properties.length; i < len; i++) {                
        var value = pos.coords[properties[i]];
                document.getElementById(properties[i]).innerHTML = value;
               
            }
            document.getElementById(&#39;timestamp&#39;).innerHTML = pos.timestamp;
        }    </script></body></html>

반환된 위치 객체에는 두 개의 속성 이 포함되어 있습니다. coords: 좌표 정보를 반환합니다. 타임스탬프: 좌표 정보를 얻은 시간입니다. 그 중 좌표에는 다음 속성이 포함됩니다: 위도: 고도, 정확도: 고도 정확도(미터), 이동 속도(미터/ 두번째) .

브라우저를 호스팅하는 기기에 따라 모든 정보가 반환되지는 않습니다. GPS, 가속도계, 나침반이 장착된 모바일 장치는 대부분의 정보를 반환하지만 가정용 컴퓨터는 그렇지 않습니다. 집에 있는 컴퓨터에서 얻는 위치정보는 네트워크 환경이나 if에 따라 다릅니다. 위 예제의 결과를 살펴보겠습니다.

좌표 정보를 얻으려면 허용을 클릭하세요.

 2. 예외 처리

이제 getCurrentPosition의 예외 처리를 소개합니다. errorCallback을 사용하여 콜백 함수를 구현했습니다. 함수에서 반환된 오류 매개변수에는 코드: 오류 유형 코드, 메시지: 오류 메시지라는 두 가지 속성이 포함되어 있습니다. 코드에는 세 가지 값이 포함되어 있습니다. 1: 사용자에게 지리적 위치를 사용할 권한이 없습니다. 2: 좌표 정보를 얻을 수 없습니다. 3: 정보를 얻는 데 시간이 초과되었습니다.

아래 예를 살펴보겠습니다.

<!DOCTYPE HTML><html><head>
    <title>Example</title>
    <style>
        table{border-collapse: collapse;}
        th, td{padding: 4px;}
        th{text-align: right;}
    </style></head><body>
    <table border="1">
        <tr>
            <th>Longitude:</th>
            <td id="longitude">-</td>
            <th>Latitude:</th>
            <td id="latitude">-</td>
        </tr>
        <tr>
            <th>Altitude:</th>
            <td id="altitude">-</td>
            <th>Accuracy:</th>
            <td id="accuracy">-</td>
        </tr>
        <tr>
            <th>Altitude Accuracy:</th>
            <td id="altitudeAccuracy">-</td>
            <th>Heading:</th>
            <td id="heading">-</td>
        </tr>
        <tr>
            <th>Speed:</th>
            <td id="speed">-</td>
            <th>Time Stamp:</th>
            <td id="timestamp">-</td>
        </tr>
        <tr>
            <th>Error Code:</th>
            <td id="errcode">-</td>
            <th>Error Message:</th>
            <td id="errmessage">-</td>
        </tr>
    </table>
    <script>
        navigator.geolocation.getCurrentPosition(displayPosition, handleError);        
        function displayPosition(pos) {            
        var properties = ["longitude", "latitude", "altitude", "accuracy", "altitudeAccuracy", "heading", "speed"];            
        for (var i = 0; i < properties.length; i++) {                
        var value = pos.coords[properties[i]];
                document.getElementById(properties[i]).innerHTML = value;
            }
            document.getElementById("timestamp").innerHTML = pos.timestamp;
        }        function handleError(err) {
            document.getElementById("errcode").innerHTML = err.code;
            document.getElementById("errmessage").innerHTML = err.message;
        }    </script></body></html>

승인 거부, 실행 결과:

 

  3. 지리적 위치 선택적 매개변수 사용

getCurrentPosition(callback,errorCallback,options)의 옵션에는 사용할 수 있는 다음 매개변수가 있습니다. maximumAge : 캐싱 시간(밀리초)을 지정합니다. 다음 예를 들어보겠습니다.

<!DOCTYPE HTML><html><head>
    <title>Example</title>
    <style>
        table{border-collapse: collapse;}
        th, td{padding: 4px;}
        th{text-align: right;}
    </style></head><body>
    <table border="1">
        <tr>
            <th>Longitude:</th>
            <td id="longitude">-</td>
            <th>Latitude:</th>
            <td id="latitude">-</td>
        </tr>
        <tr>
            <th>Altitude:</th>
            <td id="altitude">-</td>
            <th>Accuracy:</th>
            <td id="accuracy">-</td>
        </tr>
        <tr>
            <th>Altitude Accuracy:</th>
            <td id="altitudeAccuracy">-</td>
            <th>Heading:</th>
            <td id="heading">-</td>
        </tr>
        <tr>
            <th>Speed:</th>
            <td id="speed">-</td>
            <th>Time Stamp:</th>
            <td id="timestamp">-</td>
        </tr>
        <tr>
            <th>Error Code:</th>
            <td id="errcode">-</td>
            <th>Error Message:</th>
            <td id="errmessage">-</td>
        </tr>
    </table>
    <script>
        var options = {
            enableHighAccuracy: false,
            timeout: 2000,
            maximumAge: 30000
        };
        navigator.geolocation.getCurrentPosition(displayPosition, handleError, options);        
        function displayPosition(pos) {            
        var properties = ["longitude", "latitude", "altitude", "accuracy", "altitudeAccuracy", "heading", "speed"];            
        for (var i = 0; i < properties.length; i++) {                
        var value = pos.coords[properties[i]];
                document.getElementById(properties[i]).innerHTML = value;
            }
            document.getElementById("timestamp").innerHTML = pos.timestamp;
        }        function handleError(err) {
            document.getElementById("errcode").innerHTML = err.code;
            document.getElementById("errmessage").innerHTML = err.message;
        }    </script></body></html>

 4. 위치 변경 모니터링

아래에서는 watchPosition 메서드를 사용하여 위치 변경을 모니터링하는 방법을 소개합니다. . 예를 살펴보겠습니다.

<!DOCTYPE HTML><html><head>
    <title>Example</title>
    <style>
        table{border-collapse: collapse;}
        th, td{padding: 4px;}
        th{text-align: right;}
    </style></head><body>
    <table border="1">
        <tr>
            <th>Longitude:</th>
            <td id="longitude">-</td>
            <th>Latitude:</th>
            <td id="latitude">-</td>
        </tr>
        <tr>
            <th>Altitude:</th>
            <td id="altitude">-</td>
            <th>Accuracy:</th>
            <td id="accuracy">-</td>
        </tr>
        <tr>
            <th>Altitude Accuracy:</th>
            <td id="altitudeAccuracy">-</td>
            <th>Heading:</th>
            <td id="heading">-</td>
        </tr>
        <tr>
            <th>Speed:</th>
            <td id="speed">-</td>
            <th>Time Stamp:</th>
            <td id="timestamp">-</td>
        </tr>
        <tr>
            <th>Error Code:</th>
            <td id="errcode">-</td>
            <th>Error Message:</th>
            <td id="errmessage">-</td>
        </tr>
    </table>
    <button id="pressme">Cancel Watch</button>
    <script>
        var options = {
            enableHighAccuracy: false,
            timeout: 2000,
            maximumAge: 30000
        };        var watchID = navigator.geolocation.watchPosition(displayPosition, handleError, options);
        
        document.getElementById("pressme").onclick = function (e) {
            navigator.geolocation.clearWatch(watchID);
        };        function displayPosition(pos) {            
        var properties = ["longitude", "latitude", "altitude", "accuracy", "altitudeAccuracy", "heading", "speed"];            
        for (var i = 0; i < properties.length; i++) {                
        var value = pos.coords[properties[i]];
                document.getElementById(properties[i]).innerHTML = value;
            }
            document.getElementById("timestamp").innerHTML = pos.timestamp;
        }        function handleError(err) {
            document.getElementById("errcode").innerHTML = err.code;
            document.getElementById("errmessage").innerHTML = err.message;
        }    </script></body></html>

위 내용은 HTML5 가이드 (4) - Geolocation 사용에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
H5는 HTML5의 속기입니까? 세부 사항을 탐색합니다H5는 HTML5의 속기입니까? 세부 사항을 탐색합니다Apr 14, 2025 am 12:05 AM

H5는 HTML5의 약어 일뿐 만 아니라 더 넓은 현대 웹 개발 기술 생태계를 나타냅니다. 1. H5는 HTML5, CSS3, JavaScript 및 관련 API 및 기술을 포함합니다. 2. 그것은 더 풍부하고 대화식이며 부드러운 사용자 경험을 제공하며 여러 장치에서 원활하게 실행할 수 있습니다. 3. H5 기술 스택을 사용하여 반응 형 웹 페이지와 복잡한 대화식 기능을 만들 수 있습니다.

H5 및 HTML5 : 웹 개발에 일반적으로 사용되는 용어H5 및 HTML5 : 웹 개발에 일반적으로 사용되는 용어Apr 13, 2025 am 12:01 AM

H5 및 HTML5는 동일한 것을, 즉 html5를 나타냅니다. HTML5는 HTML의 다섯 번째 버전으로 시맨틱 태그, 멀티미디어 지원, 캔버스 및 그래픽, 오프라인 스토리지 및 로컬 스토리지와 같은 새로운 기능을 제공하여 웹 페이지의 표현성 및 상호 작용성을 향상시킵니다.

H5는 무엇을 언급합니까? 맥락 탐색H5는 무엇을 언급합니까? 맥락 탐색Apr 12, 2025 am 12:03 AM

h5referstohtml5, apivotaltechnologyinwebdevelopment.1) html5introducesnewelements 및 dynamicwebapplications.2) itsupp ortsmultimediawithoutplugins, enovannangeserexperienceacrossdevices.3) SemanticLementsImproveContentsTructUreAndSeo.4) H5'Srespo

H5 : 도구, 프레임 워크 및 모범 사례H5 : 도구, 프레임 워크 및 모범 사례Apr 11, 2025 am 12:11 AM

H5 개발에서 마스터 해야하는 도구 및 프레임 워크에는 vue.js, React 및 Webpack이 포함됩니다. 1.vue.js는 사용자 인터페이스를 구축하고 구성 요소 개발을 지원하는 데 적합합니다. 2. 복잡한 응용 프로그램에 적합한 가상 DOM을 통해 페이지 렌더링을 최적화합니다. 3. Webpack은 모듈 포장에 사용되며 리소스로드를 최적화합니다.

HTML5의 유산 : 현재 H5 이해HTML5의 유산 : 현재 H5 이해Apr 10, 2025 am 09:28 AM

html5hassignificallytransformedwebdevelopmentbyintranticalticlementements, 향상 Multimediasupport 및 Improvingperformance.1) itmadewebsitessmoreaccessibleadseo 친환경적 인 요소, 및 .2) Html5intagnatee

H5 코드 : 접근성 및 시맨틱 HTMLH5 코드 : 접근성 및 시맨틱 HTMLApr 09, 2025 am 12:05 AM

H5는 시맨틱 요소 및 ARIA 속성을 통해 웹 페이지 접근성 및 SEO 효과를 향상시킵니다. 1. 컨텐츠 구조를 구성하고 SEO를 개선하기 위해 사용합니다. 2. Aria-Label과 같은 ARIA 속성은 접근성을 향상시키고 보조 기술 사용자는 웹 페이지를 원활하게 사용할 수 있습니다.

H5는 html5와 동일합니까?H5는 html5와 동일합니까?Apr 08, 2025 am 12:16 AM

"H5"와 "HTML5"는 대부분의 경우 동일하지만 특정 시나리오에서는 다른 의미를 가질 수 있습니다. "HTML5"는 새로운 태그와 API를 포함하는 W3C 정의 표준입니다. "H5"는 일반적으로 HTML5의 약어이지만 모바일 개발에서는 HTML5를 기반으로 한 프레임 워크를 참조 할 수 있습니다. 이러한 차이를 이해하면 프로젝트 에서이 용어를 정확하게 사용하는 데 도움이됩니다.

H5의 기능은 무엇입니까?H5의 기능은 무엇입니까?Apr 07, 2025 am 12:10 AM

H5 또는 HTML5는 HTML의 다섯 번째 버전입니다. 개발자에게 더 강력한 도구 세트를 제공하여 복잡한 웹 애플리케이션을보다 쉽게 ​​만들 수 있습니다. H5의 핵심 기능에는 다음이 포함됩니다. 1) 웹 페이지에 그래픽 및 애니메이션을 그리는 요소; 2) 웹 페이지 구조를 SEO 최적화에 명확하고 도움이되는 시맨틱 태그 등; 3) GeolocationApi 지원 위치 기반 서비스와 같은 새로운 API; 4) 호환성 테스트 및 폴리 필 라이브러리를 통해 크로스 브라우저 호환성을 보장해야합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
1 몇 달 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.