위치정보: 지도에서 사용자 또는 기기 위치 표시

개요

이 튜토리얼에서는 브라우저의 HTML5 위치정보 기능을 Maps JavaScript API와 함께 사용하여 기기의 지리적 위치를 Google 지도에 표시하는 방법을 설명합니다. 지리적 위치는 사용자가 위치 공유를 허용한 경우에만 표시됩니다.

사용자가 위치정보 요청을 트리거하면 브라우저에서 기기의 위치 데이터에 액세스하는 데 동의하는지 묻는 메시지가 표시됩니다. 요청이 실패하면 위치 정보 액세스 권한이 거부되었거나 기기에서 위치를 확인할 수 없기 때문일 수 있습니다. 이 기능은 지원되는 일부 또는 모든 브라우저의 보안 컨텍스트 (HTTPS)에서만 사용할 수 있습니다.

다음은 사용자 기기의 현재 위치를 확인할 수 있는 지도입니다.

아래 샘플은 이 지도를 만드는 데 필요한 전체 코드를 보여줍니다.

TypeScript

// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
let map: google.maps.Map, infoWindow: google.maps.InfoWindow;

function initMap(): void {
  map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 6,
  });
  infoWindow = new google.maps.InfoWindow();

  const locationButton = document.createElement("button");

  locationButton.textContent = "Pan to Current Location";
  locationButton.classList.add("custom-map-control-button");

  map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton);

  locationButton.addEventListener("click", () => {
    // Try HTML5 geolocation.
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position: GeolocationPosition) => {
          const pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          };

          infoWindow.setPosition(pos);
          infoWindow.setContent("Location found.");
          infoWindow.open(map);
          map.setCenter(pos);
        },
        () => {
          handleLocationError(true, infoWindow, map.getCenter()!);
        }
      );
    } else {
      // Browser doesn't support Geolocation
      handleLocationError(false, infoWindow, map.getCenter()!);
    }
  });
}

function handleLocationError(
  browserHasGeolocation: boolean,
  infoWindow: google.maps.InfoWindow,
  pos: google.maps.LatLng
) {
  infoWindow.setPosition(pos);
  infoWindow.setContent(
    browserHasGeolocation
      ? "Error: The Geolocation service failed."
      : "Error: Your browser doesn't support geolocation."
  );
  infoWindow.open(map);
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
let map, infoWindow;

function initMap() {
  map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 6,
  });
  infoWindow = new google.maps.InfoWindow();

  const locationButton = document.createElement("button");

  locationButton.textContent = "Pan to Current Location";
  locationButton.classList.add("custom-map-control-button");
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton);
  locationButton.addEventListener("click", () => {
    // Try HTML5 geolocation.
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          };

          infoWindow.setPosition(pos);
          infoWindow.setContent("Location found.");
          infoWindow.open(map);
          map.setCenter(pos);
        },
        () => {
          handleLocationError(true, infoWindow, map.getCenter());
        },
      );
    } else {
      // Browser doesn't support Geolocation
      handleLocationError(false, infoWindow, map.getCenter());
    }
  });
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
  infoWindow.setPosition(pos);
  infoWindow.setContent(
    browserHasGeolocation
      ? "Error: The Geolocation service failed."
      : "Error: Your browser doesn't support geolocation.",
  );
  infoWindow.open(map);
}

window.initMap = initMap;
예 보기

샘플 사용해 보기

위치정보란 무엇인가요?

위치정보는 다양한 데이터 수집 메커니즘을 사용하여 컴퓨팅 기기의 지리적 위치를 식별하는 것을 나타냅니다. 일반적으로 대부분의 위치정보 서비스는 네트워크 라우팅 주소 또는 내부 GPS 칩을 사용하여 이 위치를 결정합니다. 위치정보는 기기에 해당하는 API입니다. 즉 웹 애플리케이션을 통해 위치정보를 사용하려면 브라우저나 기기가 위치정보를 지원해야 합니다.

W3C 위치정보 표준

위치정보를 사용하려는 애플리케이션은 W3C 위치정보 표준을 지원해야 합니다. 위의 샘플 코드에서는 W3C navigator.geolocation API를 통해 기기의 위치를 확인합니다.

웹사이트에서 기기의 위치를 감지하기 위해 IP 주소를 사용하는 경우도 있지만 이 경우 대략적인 위치만 추정할 수 있습니다. W3C 표준 API는 가장 완벽하게 지원되며 가장 정확하므로 다른 위치정보 메서드보다 우선시해야 합니다.