HTML Geolocation API

The Geolocation API lets a web page ask the browser for the user's current physical location. It is accessed through the navigator.geolocation object and always requires the user's explicit permission before any coordinates are shared.

1) Checking for Support


<script>
  if (navigator.geolocation) {
    // Geolocation API is available
  } else {
    // Not supported by this browser
  }
</script>

Always feature-detect before calling any geolocation methods.

2) getCurrentPosition(success, error)


navigator.geolocation.getCurrentPosition(showPosition, showError);

function showPosition(position) {
  var lat = position.coords.latitude;
  var lon = position.coords.longitude;
  console.log(lat, lon);
}

function showError(error) {
  console.log("Error code: " + error.code);
}

getCurrentPosition() is asynchronous — it takes a success callback (called with the position) and an optional error callback.

3) Permission and HTTPS Requirement


<!-- Modern browsers only allow Geolocation on: -->
// 1. Pages served over HTTPS
// 2. http://localhost during local development
// The browser always shows a permission prompt to the user first

If the page is loaded over plain http:// (and isn't localhost), most browsers will refuse to even ask for permission.

4) The Position Object


function showPosition(position) {
  var lat = position.coords.latitude;   // e.g. 28.6139
  var lon = position.coords.longitude;  // e.g. 77.2090
  var acc = position.coords.accuracy;   // accuracy radius in meters
}

position.coords also exposes altitude, heading, and speed when the device supports them.

5) Handling Errors


function showError(error) {
  switch (error.code) {
    case error.PERMISSION_DENIED:
      alert("User denied the request for location.");
      break;
    case error.POSITION_UNAVAILABLE:
      alert("Location information is unavailable.");
      break;
    case error.TIMEOUT:
      alert("The request to get location timed out.");
      break;
    default:
      alert("An unknown error occurred.");
  }
}

Always supply an error callback — users can deny permission, be offline, or be on a device without a location sensor.

Live Demo

Click the button below — your browser will ask for permission before sharing your location.

Best Practices:

  • Geolocation requires HTTPS (or localhost) — it will silently fail on plain HTTP in most modern browsers.
  • Always provide an error callback so denied/unavailable/timeout cases don't leave users confused.
  • Never call getCurrentPosition() automatically on page load without a clear reason — let the user trigger it via a button.
  • Use watchPosition() instead of getCurrentPosition() if you need to continuously track movement.
  • Treat coordinates as sensitive personal data — never log or transmit them without the user's knowledge.