상세 컨텐츠

본문 제목

GPS 이동하면서 위치 정보 얻는 방법

본문

반응형
  • geolocation 객체의 watchPostion()을 호출
  • watchPosition() - 사용자의 현재 위치를 연속하여 출력한다.
  • clearWatch() - watchPosition() 메서드를 중지한다.
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
</head>
<body>
  <button onclick="startGeolocation()">위치 정보 시작</button>
  <button onclick="stopGeolocation()">위치 정보 중지</button>
  <div id="target"></div>
  <script>
    let id;
    let myDiv = document.getElementById("target");
    function startGeolocation() {
      if (navigator.geolocation) {
          id = navigator.geolocation.watchPosition(showGeolocation)
      }
      function showGeolocation(location) {
        myDiv.innerHTML = "(위도: " + location.coords.latitude + ", 경도: " + location.coords.longitude + ")";
      }
      function stopGeolocation() {
        if (navigator.geolocation) {
            navigator.geolocation.clearWatch(id);
        }
      }
    }
  </script>
</body>
</html>

실시간 정보를 표시합니다.

반응형

관련글 더보기