Geolokasi: Menampilkan Posisi Perangkat atau Pengguna di Maps

Ringkasan

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

Di bawah ini adalah peta yang dapat mengidentifikasi lokasi Anda 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 pengguna atau perangkat komputasi melalui beragam mekanisme pengumpulan data. Biasanya, sebagian besar layanan geolokasi menggunakan alamat perutean jaringan atau perangkat GPS internal untuk menentukan lokasi ini. Geolocation adalah API spesifik 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 pengguna melalui properti navigator.geolocation W3C.

Sebagian browser menggunakan alamat IP untuk mendeteksi lokasi pengguna. Namun, cara ini mungkin hanya menyediakan perkiraan kasar dari lokasi pengguna. Pendekatan W3C adalah cara yang paling mudah dan paling didukung, sehingga diprioritaskan dibandingkan metode geolokasi lainnya.