地理位置:在 Google 地圖上顯示使用者或裝置位置

總覽

本教學課程說明如何使用瀏覽器的 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-standard API 是完整支援且最準確的 API,因此優先順序應高於其他地理位置方法。