Geolocation API로 현재 위치 가져오기: 웹사이트에서 사용자 위치 기반 서비스 만들기

신수정·2024년 5월 5일

Geolocation API를 사용하여 웹사이트에서 사용자의 위치 정보를 가져오는 방법에 대해 알아보겠습니다. 이를 통해 위치 기반 추천 서비스나 날씨 정보 제공 등을 구현할 수 있습니다.

Geolocation API란?

Geolocation API는 웹 브라우저에서 사용자의 위치 정보를 가져올 수 있는 표준 API입니다. GPS, Wi-Fi, 셀룰러 네트워크, IP 주소 등의 데이터를 활용하여 사용자의 현재 위치를 확인합니다.

특징

  • 사용자 동의 필수: 브라우저는 사용자의 위치 정보를 수집하기 전 동의를 요구합니다.
  • 다양한 위치 수집 소스: GPS, Wi-Fi, 셀룰러 네트워크, IP 주소 등 여러 소스로부터 정보를 수집합니다.
  • 높은 정확도 지원: enableHighAccuracy 옵션을 통해 정확도를 조정할 수 있습니다.
  • 브라우저 지원: 대부분의 현대 브라우저에서 지원되며, 모바일에서도 동작합니다.

Geolocation API 사용 방법

Geolocation API는 주로 두 가지 주요 메서드를 통해 사용됩니다.

  1. getCurrentPosition: 한 번만 위치를 가져옵니다.
  2. watchPosition: 위치가 변할 때마다 지속적으로 위치 정보를 제공합니다.

위치 권한 요청 및 가져오기

먼저, getCurrentPosition 메서드를 사용하여 현재 위치 정보를 가져오는 예시를 보여드리겠습니다.

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>Geolocation API 사용 예시</title>
</head>
<body>
  <h1>Geolocation API로 현재 위치 가져오기</h1>
  <button onclick="getLocation()">위치 찾기</button>
  <p id="status">위치를 찾지 못했습니다</p>
  <script>
    function getLocation() {
      const status = document.getElementById("status");

      // Geolocation API 지원 여부 확인
      if ("geolocation" in navigator) {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            const { latitude, longitude, accuracy } = position.coords;
            status.textContent = `위도: ${latitude}, 경도: ${longitude}, 정확도: ${accuracy}미터`;
          },
          (error) => {
            status.textContent = `위치 정보를 가져올 수 없습니다: ${error.message}`;
          },
          {
            enableHighAccuracy: true, // 정확도 우선 모드
            timeout: 10000,           // 10초 이내에 응답 없으면 에러 발생
            maximumAge: 0             // 항상 최신 위치 정보 수집
          }
        );
      } else {
        status.textContent = "브라우저가 위치 서비스를 지원하지 않습니다.";
      }
    }
  </script>
</body>
</html>

Geolocation API 옵션 설명

navigator.geolocation.getCurrentPositionnavigator.geolocation.watchPosition 메서드에는 선택할 수 있는 옵션들이 있습니다.

  • enableHighAccuracy: 고정밀 모드를 활성화합니다. 배터리 소모가 높아질 수 있습니다.
  • timeout: 위치 정보를 가져올 때까지 기다리는 최대 시간을 밀리초 단위로 설정합니다.
  • maximumAge: 캐시된 위치 정보가 제공될 수 있는 최대 시간을 밀리초 단위로 설정합니다.

위치 업데이트 실시간 추적

watchPosition 메서드를 사용하면 사용자의 위치 변화를 실시간으로 추적할 수 있습니다.

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>Geolocation API 실시간 위치 추적</title>
</head>
<body>
  <h1>Geolocation API로 실시간 위치 추적하기</h1>
  <button onclick="startTracking()">실시간 추적 시작</button>
  <button onclick="stopTracking()">추적 중지</button>
  <p id="status">위치를 찾지 못했습니다</p>
  <script>
    let watchId;

    function startTracking() {
      const status = document.getElementById("status");

      // Geolocation API 지원 여부 확인
      if ("geolocation" in navigator) {
        watchId = navigator.geolocation.watchPosition(
          (position) => {
            const { latitude, longitude, accuracy } = position.coords;
            status.textContent = `위도: ${latitude}, 경도: ${longitude}, 정확도: ${accuracy}미터`;
          },
          (error) => {
            status.textContent = `위치 정보를 가져올 수 없습니다: ${error.message}`;
          },
          {
            enableHighAccuracy: true, // 정확도 우선 모드
            timeout: 10000,           // 10초 이내에 응답 없으면 에러 발생
            maximumAge: 0             // 항상 최신 위치 정보 수집
          }
        );
      } else {
        status.textContent = "브라우저가 위치 서비스를 지원하지 않습니다.";
      }
    }

    function stopTracking() {
      navigator.geolocation.clearWatch(watchId);
      document.getElementById("status").textContent = "위치 추적이 중지되었습니다.";
    }
  </script>
</body>
</html>

Geolocation API 활용 예시: 나들이 장소 추천하기

실제 예시로, Geolocation API를 사용하여 주변의 나들이 장소를 추천해 보겠습니다. 이를 위해 카카오맵 API와 연동해보겠습니다.

카카오맵 API 연동 및 키워드 검색

  1. 카카오 개발자 페이지 가입 및 앱 키 발급

  2. 카카오맵 API 스크립트 추가

    • index.html 파일에 다음 스크립트를 추가합니다.
<script type="text/javascript" src="//dapi.kakao.com/v2/maps/sdk.js?appkey=YOUR_APP_KEY&libraries=services"></script>
  • YOUR_APP_KEY 부분에 발급받은 JavaScript 키를 입력하세요.
  1. 주변 장소 검색 코드 작성
    • Geolocation API를 사용해 사용자의 현재 위치를 찾고, 카카오맵 API를 사용해 주변 관광지 장소를 추천해 보겠습니다.
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>나들이 장소 추천</title>
  <script type="text/javascript" src="//dapi.kakao.com/v2/maps/sdk.js?appkey=YOUR_APP_KEY&libraries=services"></script>
</head>
<body>
  <h1>Geolocation API로 나들이 장소 추천하기</h1>
  <button onclick="getLocation()">주변 인기 장소 찾기</button>
  <p id="status">위치를 찾지 못했습니다</p>
  <div id="map" style="width:500px;height:400px;"></div>
  <ul id="places"></ul>
  <script>
    let map;
    let ps;

    function getLocation() {
      const status = document.getElementById("status");
      
      if ("geolocation" in navigator) {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            const { latitude, longitude } = position.coords;
            status.textContent = `위도: ${latitude}, 경도: ${longitude}`;
            
            // 지도를 해당 위치로 이동
            const mapContainer = document.getElementById('map');
            const mapOption = {
              center: new kakao.maps.LatLng(latitude, longitude),
              level: 4
            };
            map = new kakao.maps.Map(mapContainer, mapOption);
            
            // 마커 표시
            const marker = new kakao.maps.Marker({
              position: new kakao.maps.LatLng(latitude, longitude)
            });
            marker.setMap(map);

            // 장소 검색 객체 생성
            ps = new kakao.maps.services.Places();
            
            // 주변 나들이 장소 검색
            const placesList = document.getElementById("places");
            ps.keywordSearch("관광지", (data, status, pagination) => {
              if (status === kakao.maps.services.Status.OK) {
                placesList.innerHTML = "";
                data.forEach((place) => {
                  const listItem = document.createElement("li");
                  listItem.textContent = `${place.place_name} (${place.address_name})`;
                  placesList.appendChild(listItem);
                  
                  // 지도에 마커 추가
                  const placeMarker = new kakao.maps.Marker({
                    position: new kakao.maps.LatLng(place.y, place.x),
                    map: map
                  });
                });
              } else {
                placesList.textContent = "주변 관광지를 찾을 수 없습니다.";
              }
            }, {
              location: new kakao.maps.LatLng(latitude, longitude),
              radius: 5000 // 5km 내에서 검색
            });
          },
          (error) => {
            status.textContent = `위치 정보를 가져올 수 없습니다: ${error.message}`;
          }
        );
      } else {
        status.textContent = "브라우저가

 위치 서비스를 지원하지 않습니다.";
      }
    }
  </script>
</body>
</html>

Geolocation API를 사용하여 사용자 위치를 얻는 방법과 이를 활용해 주변 나들이 장소를 추천하는 예시를 만들어보았습니다.

참고 자료

profile
안녕하세요:)

0개의 댓글