HTML Geolocation


The HTML Geolocation API allows web applications to access the geographical location of a user's device. It can retrieve:

  • Latitude

  • Longitude

  • Accuracy

  • Altitude (if available)

  • Speed and direction (if available)

⚠️ Note: This feature works only in secure contexts (HTTPS), and the user must grant permission.


🔹 Basic Syntax

navigator.geolocation.getCurrentPosition(successCallback, errorCallback);

🔹 Example: Get Current Position

<button onclick="getLocation()">Get Location</button>
<p id="output"></p>

<script>
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition, showError);
  } else {
    document.getElementById("output").innerText = "Geolocation is not supported.";
  }
}

function showPosition(position) {
  document.getElementById("output").innerText =
    "Latitude: " + position.coords.latitude +
    ", Longitude: " + position.coords.longitude;
}

function showError(error) {
  switch (error.code) {
    case error.PERMISSION_DENIED:
      alert("User denied the request.");
      break;
    case error.POSITION_UNAVAILABLE:
      alert("Location unavailable.");
      break;
    case error.TIMEOUT:
      alert("Request timed out.");
      break;
    case error.UNKNOWN_ERROR:
      alert("An unknown error occurred.");
      break;
  }
}
</script>

🔹 Geolocation Methods

Method Description
getCurrentPosition() Gets the current location once
watchPosition() Monitors and returns location continuously
clearWatch(id) Stops monitoring the position

Practice Questions

Q1. Use navigator.geolocation.getCurrentPosition() to show latitude and longitude.

Q2. Add a button that fetches location on click.

Q3. Display an error message if the user denies location permission.

Q4. Use watchPosition() to track real-time movement.

Q5. Display a live Google Maps link using the coordinates.

Q6. Show coordinates only when accessed over HTTPS.

Q7. Log errors for debugging using showError() function.

Q8. Update a <div> with coordinates every 5 seconds using watchPosition.

Q9. Create a fallback message for unsupported browsers.

Q10. Use clearWatch() to stop location tracking with a "Stop" button.


Go Back Top