Bhylu

Geolocation API

Geolocation can request an estimated device position after the visitor makes a relevant choice. It needs a secure context, appropriate policy permissions, and the visitor’s permission.

How it works

  • Explain why location is useful before requesting it, and offer a manual alternative. Do not repeatedly prompt after someone declines.
  • getCurrentPosition takes success and error callbacks. Accuracy is an estimate in metres, not a promise that the visitor is at an exact address.
  • HTTPS is the normal production context. Localhost is commonly treated as trustworthy for development, but embedding and Permissions-Policy can add restrictions.

A practical example

HTML

<button id="locate" type="button">Use my location</button>
<p id="location-status" role="status"></p>
<script>
  const status = document.getElementById('location-status');
  document.getElementById('locate').addEventListener('click', () => {
    if (!('geolocation' in navigator)) { status.textContent = 'Enter your area manually.'; return; }
    navigator.geolocation.getCurrentPosition(
      position => { status.textContent = 'Estimated accuracy: ' + Math.round(position.coords.accuracy) + ' metres.'; },
      () => { status.textContent = 'Location unavailable. Enter your area manually.'; },
      { timeout: 10000, maximumAge: 60000 }
    );
  });
</script>

In a suitable local or HTTPS page, the browser asks permission after the button is activated. This example displays only the accuracy and does not send coordinates anywhere.