Ubicación geográfica: cómo mostrar la posición de un usuario o un dispositivo en Maps

Descripción general

En este instructivo, se explica cómo mostrar la ubicación geográfica de un dispositivo en un mapa de Google Maps usando la función de ubicación geográfica HTML5 de tu navegador y la API de Maps JavaScript. La ubicación geográfica solo se mostrará si el usuario permitió el uso compartido de la ubicación.

Cuando el usuario active la solicitud de ubicación geográfica, recibirá un mensaje del navegador en el que se le solicitará su consentimiento para acceder a los datos de ubicación del dispositivo. Si la solicitud falla, podría deberse a que se rechazaron los permisos de ubicación o a que el dispositivo no pudo determinar su ubicación. Esta función solo está disponible en contextos seguros (HTTPS), en algunos o todos los navegadores compatibles.

A continuación, se muestra un mapa que puede identificar la ubicación actual del dispositivo del usuario.

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 hace referencia a la identificación de la ubicación geográfica de un dispositivo informático a través de una variedad de 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 chips de GPS internos para determinar esta 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 dispositivo mediante la API de navigator.geolocation de W3C.

A veces, los sitios web usan direcciones IP para detectar la ubicación de un dispositivo. Sin embargo, esto solo proporciona una estimación aproximada de esa ubicación. Las APIs estándar de W3C son las más compatibles y más precisas, por lo que deben priorizarse sobre otros métodos de ubicación geográfica.