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

개요

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

아래 지도에서는 사용자의 현재 위치를 확인할 수 있습니다.

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

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 속성을 통해 사용자의 위치를 결정합니다.

일부 브라우저는 IP 주소를 사용하여 사용자의 위치를 감지합니다. 하지만 IP 주소를 통해 사용자의 대략적인 위치만 확인할 수도 있습니다. W3C 접근방식은 가장 쉽고 완벽하게 지원되므로 다른 위치정보 메서드보다 우선 적용하는 것이 좋습니다.