Geolokasi: Menampilkan Posisi Perangkat atau Pengguna di Maps

Ringkasan

Tutorial ini menampilkan cara menampilkan lokasi geografis perangkat pada peta Google, menggunakan fitur Geolokasi HTML5 browser Anda beserta Maps JavaScript API. Tujuan lokasi geografis hanya akan ditampilkan jika pengguna telah mengizinkan berbagi lokasi.

Saat pengguna memicu permintaan geolokasi, mereka akan menerima perintah dari browser untuk izin mengakses data lokasi perangkat. Jika permintaan gagal, hal itu bisa disebabkan izin akses lokasi ditolak, atau karena perangkat tidak dapat menentukan lokasinya. Fitur ini hanya tersedia dalam konteks aman (HTTPS), di beberapa atau semua browser yang mendukung.

Di bawah ini adalah peta yang dapat mengidentifikasi lokasi perangkat pengguna saat ini.

Contoh berikut menampilkan keseluruhan kode yang Anda perlukan untuk membuat peta ini.

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;
Lihat contoh

Mencoba Contoh

Apa yang dimaksud dengan Geolokasi?

Geolokasi mengacu pada identifikasi lokasi geografis perangkat komputasi menggunakan berbagai mekanisme pengumpulan data. Biasanya, sebagian besar layanan geolokasi menggunakan jaringan alamat perutean atau chip GPS internal untuk menentukan lokasi ini. Geolocation adalah API spesifik per perangkat. Artinya, browser atau perangkat harus mendukung geolokasi agar dapat menggunakannya melalui aplikasi web.

Standar Geolokasi W3C

Aplikasi yang ingin menjalankan geolokasi harus mendukung standar Geolokasi W3C. Perhatikan bahwa kode contoh di atas menentukan lokasi perangkat melalui W3C API navigator.geolocation.

Terkadang situs web menggunakan alamat IP untuk mendeteksi lokasi perangkat, namun ini hanya dapat memberikan perkiraan kasar lokasi tersebut. API standar W3C adalah yang paling didukung dan paling akurat, sehingga harus diprioritaskan daripada metode geolokasi lainnya.