SmartCodingTips

HTML5 Geolocation API

The Geolocation API in HTML5 allows web applications to access the user's geographical location, with their permission. This is useful for location-based services such as maps, weather updates, and check-ins.

Basic Usage

To get the user's location, you use the navigator.geolocation.getCurrentPosition() method.


<button onclick="getLocation()">Get My Location</button>

<p id="location"></p>

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

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

function showError(error) {
  document.getElementById("location").innerText = "Error: " + error.message;
}
</script>
            

Methods in Geolocation API

  • getCurrentPosition() – Gets the current position once.
  • watchPosition() – Tracks position continuously.
  • clearWatch() – Stops watching position.

Location Object Properties

  • coords.latitude – The latitude as a decimal.
  • coords.longitude – The longitude as a decimal.
  • coords.accuracy – Accuracy of the location in meters.
  • coords.altitude – The altitude in meters (if available).
  • timestamp – The time the position was retrieved.