Géolocalisation : affichage de l'emplacement d'un utilisateur ou d'un appareil sur une carte

Présentation

Ce tutoriel explique comment afficher l'emplacement géographique d'un utilisateur ou d'un appareil sur une carte Google en utilisant la fonctionnalité Géolocalisation HTML5 de votre navigateur ainsi que l'API Maps JavaScript. Notez que l'emplacement géographique d'un utilisateur ne s'affiche que s'il a autorisé le partage de position.

La carte ci-dessous permet d'identifier votre position actuelle.

L'exemple ci-dessous montre tout le code dont vous avez besoin pour créer cette carte.

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;
Voir un exemple

Essayer l'exemple

Qu'est-ce que la géolocalisation ?

La géolocalisation est l'identification de l'emplacement géographique d'un utilisateur ou d'un appareil informatique par le biais de divers mécanismes de collecte de données. La plupart des services de géolocalisation s'appuient sur des adresses d'acheminement réseau ou des appareils GPS internes pour déterminer cette position. L'API de géolocalisation est spécifique à chaque appareil. En d'autres termes, les navigateurs et appareils doivent être compatibles avec la géolocalisation pour pouvoir l'utiliser dans les applications Web.

Norme de géolocalisation W3C

Les applications qui souhaitent utiliser la géolocalisation doivent respecter la norme de géolocalisation W3C. Notez que l'exemple de code ci-dessus détermine l'emplacement de l'utilisateur via la propriété W3C navigator.geolocation.

Certains navigateurs utilisent les adresses IP pour détecter la position des utilisateurs. Toutefois, cette méthode risque de ne fournir qu'une valeur approximative de l'emplacement de l'utilisateur. L'approche W3C est la plus facile et la mieux acceptée. C'est donc la méthode de géolocalisation à privilégier.