Geolocation: Cómo mostrar la posición de un usuario o un dispositivo en Maps

Descripción general

En este instructivo, te indicamos cómo mostrar la ubicación geográfica de un usuario o un dispositivo en un mapa de Google mediante la función Geolocation HTML5 de tu navegador y la API de Maps JavaScript. (Ten en cuenta que la ubicación geográfica de un usuario solo se muestra si este permite compartir su ubicación).

A continuación, se muestra un mapa que permite identificar tu ubicación actual.

En el siguiente ejemplo, se muestra el código completo que necesitas para crear este mapa.

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;
Ver ejemplo

Prueba la muestra

¿Qué es la ubicación geográfica?

La ubicación geográfica permite identificar dónde se encuentran un usuario o un dispositivo mediante diferentes mecanismos de recopilación de datos. Por lo general, la mayoría de los servicios de ubicación geográfica usan direcciones de enrutamiento de red o dispositivos GPS internos para determinar la ubicación. La API de Geolocation es específica según el dispositivo. Esto significa que los navegadores o dispositivos deben admitir la ubicación geográfica para poder usarla a través de aplicaciones web.

Estándar de ubicación geográfica de W3C

Las aplicaciones que deseen realizar ubicaciones geográficas deben admitir el estándar de ubicación geográfica de W3C. Ten en cuenta que el código de muestra anterior determina la ubicación del usuario a través de la propiedad navigator.geolocation de W3C.

Algunos navegadores usan direcciones IP para detectar la ubicación de un usuario. No obstante, esto puede brindar solo una ubicación estimada del usuario. El enfoque W3C es el más sencillo y el más admitido, por lo cual debería priorizarse ante otros métodos de ubicación geográfica.