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 Google utilizzando la funzionalità di geolocalizzazione HTML5 del browser insieme all'API Maps JavaScript. La posizione geografica verrà visualizzata solo se l'utente ha consentito la condivisione della posizione.

Quando l'utente attiva la richiesta di geolocalizzazione, riceverà 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 o che il dispositivo non è riuscito a determinare la sua posizione. Questa funzionalità è disponibile solo in contesti sicuri (HTTPS) e in alcuni o tutti i browser supportati.

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

L'esempio di seguito 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?

La geolocalizzazione fa riferimento all'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 della rete o chip GPS interni per determinare questa posizione. Geolocation è un'API specifica del dispositivo. Ciò significa che i browser o i dispositivi devono supportare la geolocalizzazione per poterla utilizzare tramite applicazioni web.

Standard di geolocalizzazione W3C

Le applicazioni che vogliono eseguire la geolocalizzazione devono supportare lo standard W3C Geolocation. Tieni presente che il codice campione sopra riportato determina la posizione 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 questi potrebbero fornire solo una stima approssimativa della posizione in questione. Le API standard W3C sono le più completamente supportate e accurate, per cui dovrebbero avere la priorità rispetto ad altri metodi di geolocalizzazione.