Geolocation Form: Get User Location With HTML

by Admin 46 views
Geolocation Form: Get User Location with HTML

Hey guys! Ever needed to grab a user's location and automatically feed it into a form? This guide will walk you through creating a simple HTML page that does just that. We'll use geolocation to pinpoint the user's location and then redirect them to a form with the coordinates already filled in. Let's dive in!

Setting Up the HTML Structure

First, let's create the basic HTML structure. This includes setting up the viewport for mobile devices, defining the character set, and linking to our CSS for styling. The title tag is crucial for SEO and user experience, so make sure it's descriptive and concise. Here’s the initial setup:

<!DOCTYPE html>
<html lang="es">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>INSIGNIA – Registro con ubicación</title>
    <style>
      body {
        font-family: 'Segoe UI', Arial, sans-serif;
        background: #f4f6fa;
        color: #2f3640;
        text-align: center;
        padding: 40px 20px;
      }
      h2 {
        color: #273c75;
      }
      .loader {
        margin: 30px auto;
        border: 6px solid #dcdde1;
        border-top: 6px solid #273c75;
        border-radius: 50%;
        width: 50px;
        height: 50px;
        animation: spin 1s linear infinite;
      }
      @keyframes spin {
        to {
          transform: rotate(360deg);
        }
      }
      p {
        max-width: 300px;
        margin: auto;
      }
      button {
        background: #273c75;
        color: white;
        border: none;
        border-radius: 10px;
        padding: 12px 20px;
        margin-top: 20px;
        font-size: 16px;
      }
      button:active {
        background: #192a56;
      }
    </style>
  </head>
  <body>
    <h2>🌍 Detectando tu ubicación</h2>
    <div class="loader"></div>
    <p id="status">Por favor, permite el acceso a tu ubicación para continuar.</p>
    <button id="retryBtn" style="display:none;">Intentar de nuevo</button>

    <script>
      // URL del formulario con el campo "Localización"
      const formURL =
        "https://docs.google.com/forms/d/e/1FAIpQLSdy8R5eKvUKI43tx87cVzFP3q4cyfGNvbZKihnrFsY9nPVdHA/viewform?usp=pp_url&entry.554704150=";

      const status = document.getElementById("status");
      const retryBtn = document.getElementById("retryBtn");

      function getLocation() {
        retryBtn.style.display = "none";
        status.innerText = "🔍 Solicitando acceso a tu ubicación...";
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(
            showPosition,
            showError,
            { enableHighAccuracy: true, timeout: 15000 }
          ); 
        } else {
          status.innerText = "Tu navegador no soporta geolocalización.";
        }
      }

      function showPosition(position) {
        const lat = position.coords.latitude.toFixed(6);
        const lon = position.coords.longitude.toFixed(6);
        status.innerText = "✅ ¡Ubicación detectada! Abriendo el formulario...";
        // Redirigir usando _blank para mayor compatibilidad móvil
        setTimeout(() => {
          window.open(formURL + lat + "," + lon, "_blank");
        }, 1200);
      }

      function showError(error) {
        retryBtn.style.display = "inline-block";
        switch (error.code) {
          case error.PERMISSION_DENIED:
            status.innerText =
              "❌ Acceso denegado. Permite la ubicación y vuelve a intentar.";
            break;
          case error.POSITION_UNAVAILABLE:
            status.innerText = "⚠️ No se pudo obtener la ubicación.";
            break;
          case error.TIMEOUT:
            status.innerText = "⏳ Tiempo de espera agotado.";
            break;
          default:
            status.innerText = "❗ Error al obtener la ubicación.";
        }
      }

      retryBtn.onclick = getLocation;
      getLocation();
    </script>
  </body>
</html>

CSS Styling for a Better User Experience

Good styling enhances the user experience. The CSS in the <style> tag makes the page visually appealing and user-friendly. Font selection, background color, and the loader animation are all designed to keep the user engaged while the location is being detected. Centering the text and providing sufficient padding ensures readability on various devices. The styling of the button, including the hover effect, adds a touch of interactivity.

Key Elements:

  • Font-family: Segoe UI, Arial, sans-serif for readability.
  • Background: #f4f6fa for a clean look.
  • Loader: Animated spinner to indicate loading.
  • Button: Clear visual cues for interaction.

Implementing Geolocation

Now for the juicy part: geolocation! We’ll use the navigator.geolocation API to get the user's coordinates. This API is available in most modern browsers, but it's a good idea to check for its existence before using it. This involves creating a function that prompts the user for their location and handles both success and error scenarios. Let's break down the JavaScript part.

The getLocation() Function

This function is the heart of our geolocation process. It first hides the retry button and updates the status text to inform the user that we're requesting their location. Then, it checks if the navigator.geolocation object exists. If it does, it calls the getCurrentPosition() method. This method takes three arguments:

  1. showPosition: A callback function that's called when the location is successfully retrieved.
  2. showError: A callback function that's called when there's an error.
  3. An options object: This allows us to specify options such as enableHighAccuracy and timeout. Setting enableHighAccuracy to true tells the browser to use the most accurate method possible, like GPS, but it may take longer. The timeout option specifies how long to wait for a response.
function getLocation() {
  retryBtn.style.display = "none";
  status.innerText = "🔍 Solicitando acceso a tu ubicación...";
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      showPosition,
      showError,
      { enableHighAccuracy: true, timeout: 15000 }
    );
  } else {
    status.innerText = "Tu navegador no soporta geolocalización.";
  }
}

Handling Success: The showPosition() Function

If the location is successfully retrieved, the showPosition() function is called. This function receives a position object containing the latitude and longitude. We extract these values, round them to six decimal places for precision, and then update the status text to let the user know that their location has been detected. After a short delay (1.2 seconds), we redirect the user to the form, appending the latitude and longitude as parameters. Using window.open(formURL + lat + "," + lon, "_blank"); ensures the form opens in a new tab, providing a smoother user experience, especially on mobile devices.

function showPosition(position) {
  const lat = position.coords.latitude.toFixed(6);
  const lon = position.coords.longitude.toFixed(6);
  status.innerText = "✅ ¡Ubicación detectada! Abriendo el formulario...";
  // Redirigir usando _blank para mayor compatibilidad móvil
  setTimeout(() => {
    window.open(formURL + lat + "," + lon, "_blank");
  }, 1200);
}

Handling Errors: The showError() Function

Things don't always go as planned. The showError() function handles various error scenarios. The error object contains a code property that indicates the type of error. We use a switch statement to handle different error codes:

  • PERMISSION_DENIED: The user denied the request for location information. We update the status text to inform the user that they need to grant permission.
  • POSITION_UNAVAILABLE: The location information is unavailable. This could be due to various reasons, such as the GPS being turned off.
  • TIMEOUT: The request timed out. This means that the browser was unable to retrieve the location within the specified timeout period.
  • DEFAULT: A generic error message for any other errors.

In all error cases, we display the retry button, allowing the user to try again. Error handling is crucial for a robust user experience.

function showError(error) {
  retryBtn.style.display = "inline-block";
  switch (error.code) {
    case error.PERMISSION_DENIED:
      status.innerText =
        "❌ Acceso denegado. Permite la ubicación y vuelve a intentar.";
      break;
    case error.POSITION_UNAVAILABLE:
      status.innerText = "⚠️ No se pudo obtener la ubicación.";
      break;
    case error.TIMEOUT:
      status.innerText = "⏳ Tiempo de espera agotado.";
      break;
    default:
      status.innerText = "❗ Error al obtener la ubicación.";
  }
}

Putting It All Together

Finally, we need to attach the getLocation() function to the retryBtn's onclick event and call it when the page loads. This ensures that the geolocation process starts automatically when the page is opened. The retryBtn.onclick = getLocation; line sets up the retry button to call the getLocation function when clicked, and getLocation(); at the end of the script triggers the initial location request.

retryBtn.onclick = getLocation;
getLocation();

Conclusion

And that's it! You've created a simple HTML page that uses geolocation to get the user's location and automatically redirect them to a form with the coordinates filled in. Remember to handle errors gracefully and provide clear instructions to the user. This approach is excellent for applications that require location data, such as event check-ins, surveys, and more. Have fun building awesome things, guys!