Geolokasi: Menampilkan Posisi Perangkat atau Pengguna di Maps

Ringkasan

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

Saat memicu permintaan geolokasi, pengguna akan menerima permintaan izin dari browser untuk mengakses data lokasi perangkat. Jika permintaan gagal, mungkin karena 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 merujuk pada identifikasi lokasi geografis perangkat komputasi yang menggunakan berbagai mekanisme pengumpulan data. Biasanya, sebagian besar layanan geolokasi menggunakan alamat perutean jaringan 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 navigator.geolocation API W3C.

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