Geolocalizzazione: visualizzazione della posizione dell'utente o del dispositivo su Maps

Panoramica

Questo tutorial mostra come visualizzare la posizione geografica di un utente o di un dispositivo su una mappa Google utilizzando la funzionalità di geolocalizzazione HTML5 del browser insieme all'API Maps JavaScript. Tieni presente che la posizione geografica di un utente viene visualizzata solo se ha consentito la condivisione della posizione.

Di seguito è riportata una mappa che può identificare la tua posizione attuale.

Il seguente esempio mostra l'intero codice necessario per creare questa mappa.

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;
Visualizza esempio

Prova Samples

Che cos'è la geolocalizzazione?

La geolocalizzazione fa riferimento all'identificazione della posizione geografica di un utente o di un dispositivo di elaborazione attraverso una serie di meccanismi di raccolta dei dati. In genere, la maggior parte dei servizi di geolocalizzazione utilizza indirizzi di routing della rete o dispositivi GPS interni per determinare questa posizione. La geolocalizzazione è un'API specifica del dispositivo. Ciò significa che browser o dispositivi devono supportare la geolocalizzazione per poter essere utilizzata tramite applicazioni web.

Standard di geolocalizzazione W3C

Le applicazioni che desiderano eseguire la geolocalizzazione devono supportare lo standard W3C Geolocation. Tieni presente che il codice campione riportato sopra determina la località dell'utente tramite la proprietà W3C navigator.geolocation.

Alcuni browser utilizzano gli indirizzi IP per rilevare la posizione di un utente. Tuttavia, potrebbe fornire solo una stima approssimativa della posizione dell'utente. L'approccio W3C è il più semplice e completamente supportato, perciò deve avere la priorità rispetto ad altri metodi di geolocalizzazione.