HTML - Geolocation API

Overview

Estimated time: 20–30 minutes

Geolocation requires HTTPS and user permission. Always provide fallbacks.

Example

<button id="loc">Get Location</button>
<pre id="out"></pre>
<script>
  document.getElementById('loc').addEventListener('click', () => {
    if (!('geolocation' in navigator)) {
      out.textContent = 'Geolocation not supported';
      return;
    }
    navigator.geolocation.getCurrentPosition(
      pos => { out.textContent = JSON.stringify({lat: pos.coords.latitude, lon: pos.coords.longitude}, null, 2); },
      err => { out.textContent = 'Error: ' + err.message; },
      { enableHighAccuracy: true, timeout: 8000 }
    );
  });
</script>

Common Pitfalls

  • Calling without a user gesture—may be blocked.
  • No error handling for denied permissions.