freecoding.school100% FREE · NO SIGNUP
Input HarborISSUE #28 of 46

geolocation · lat · lon · permission

FormaVSCaptain Invalid Input
Forma saysThe Geolocation API asks the user for their location — always permission-gated, never silent.

navigator.geolocation.getCurrentPosition(success, error) requests the device's coordinates. The browser shows a permission prompt; if the user allows, your success callback gets a position with coords.latitude and coords.longitude.

It can fail or be denied, so always pass an error callback. Use watchPosition for live tracking (and clearWatch to stop). Geolocation only works over HTTPS (or localhost) for privacy.

Power-ups you unlock

Captain Invalid Input attacks — common mistakes

Boss battleAdd a button that requests location and prints lat/lon, with a graceful message if the user denies.

Example code

<!doctype html>
<html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:sans-serif;padding:20px">
  <button id="b" style="font:inherit;color:#b388ff;background:none;border:1px solid #b388ff;padding:8px 14px;border-radius:3px">find me</button>
  <pre id="out" style="margin-top:12px"></pre>
  <script>
    document.getElementById('b').onclick = () => {
      const out = document.getElementById('out');
      if(!('geolocation' in navigator)) return out.textContent = 'no geolocation here';
      navigator.geolocation.getCurrentPosition(
        p => out.textContent = 'lat ' + p.coords.latitude.toFixed(3) + ' · lon ' + p.coords.longitude.toFixed(3),
        e => out.textContent = 'denied or unavailable: ' + e.message
      );
    };
  </script>
</body></html>
▶ Open the interactive comic issue
‹ Web Apis · The Platform SurfaceDrag And Drop · Draggable · Datatransfer ›