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

Panoramica

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

Quando l'utente attiva la richiesta di geolocalizzazione, riceve dal browser una richiesta di consenso per accedere ai dati sulla posizione del dispositivo. Se la richiesta non va a buon fine, il motivo potrebbe essere che le autorizzazioni di accesso alla posizione sono state negate oppure il dispositivo non è riuscito a determinarne la posizione. Questa funzionalità è disponibile solo in contesti sicuri (HTTPS), in alcuni o tutti i browser supportati.

Di seguito è riportata una mappa che può identificare la posizione attuale del dispositivo dell'utente.

L'esempio seguente 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 Sample

Che cos'è la geolocalizzazione?

Per geolocalizzazione si intende l'identificazione della posizione geografica di un dispositivo di elaborazione utilizzando una serie di meccanismi di raccolta dei dati. In genere, la maggior parte dei servizi di geolocalizzazione utilizza indirizzi di routing di rete o chip GPS interni per determinare questa posizione. La geolocalizzazione è un'API specifica per il dispositivo. Ciò significa che i browser o i dispositivi devono supportare la geolocalizzazione per poter essere utilizzata tramite applicazioni web.

Standard di geolocalizzazione W3C

Le applicazioni che vogliono eseguire la geolocalizzazione devono supportare lo standard di geolocalizzazione W3C. Tieni presente che il codice campione riportato sopra determina la località del dispositivo tramite l'API navigator.geolocation di W3C.

A volte i siti web utilizzano gli indirizzi IP per rilevare la posizione di un dispositivo, ma potrebbe fornire solo una stima approssimativa di questa posizione. Le API standard W3C sono le più supportate e precise, pertanto devono avere la priorità rispetto ad altri metodi di geolocalizzazione.