Định vị vị trí: Hiển thị vị trí của người dùng hoặc thiết bị trên Maps

Tổng quan

Hướng dẫn này cho bạn biết cách hiển thị vị trí địa lý của người dùng hoặc thiết bị trên bản đồ Google, bằng cách sử dụng tính năng Định vị vị trí HTML5 của trình duyệt cùng với API JavaScript cho Maps. (Xin lưu ý rằng vị trí địa lý của người dùng sẽ chỉ hiển thị nếu họ đã cho phép chia sẻ vị trí.)

Dưới đây là bản đồ có thể xác định vị trí hiện tại của bạn.

Mẫu bên dưới cho thấy toàn bộ mã bạn cần để tạo bản đồ này.

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;
Xem ví dụ

Thử đọc mẫu

Định vị vị trí là gì?

Định vị địa lý là việc xác định vị trí địa lý của người dùng hoặc thiết bị điện toán thông qua nhiều cơ chế thu thập dữ liệu. Thông thường, hầu hết các dịch vụ định vị vị trí đều sử dụng địa chỉ định tuyến mạng hoặc thiết bị GPS bên trong để xác định vị trí này. Định vị vị trí là một API dành riêng cho thiết bị. Điều này có nghĩa là các trình duyệt hoặc thiết bị phải hỗ trợ vị trí địa lý để sử dụng được thông qua các ứng dụng web.

Tiêu chuẩn vị trí địa lý W3C

Những ứng dụng muốn thực hiện định vị vị trí phải hỗ trợ Tiêu chuẩn định vị vị trí W3C. Xin lưu ý rằng mã mẫu ở trên sẽ xác định vị trí của người dùng thông qua thuộc tính navigator.geolocation W3C.

Một số trình duyệt sử dụng địa chỉ IP để phát hiện vị trí của người dùng. Tuy nhiên, công cụ này chỉ có thể cung cấp thông tin ước tính gần đúng về vị trí của người dùng. Phương pháp W3C là phương pháp dễ dàng nhất và được hỗ trợ đầy đủ nhất. Vì vậy, phương pháp này nên được ưu tiên hơn các phương pháp định vị vị trí khác.