H

HTML Handbook

Clean • Professional

HTML Geolocation API

3 minute

HTML Geolocation API

The Geolocation API lets websites access the user’s location (with permission). This is widely used in maps, food delivery apps, ride-booking, and weather updates.

Key Features:

  • Access the user’s current location (latitude & longitude)
  • Requires user permission for privacy.
  • Can work with GPS, Wi-Fi, or mobile networks.

How Does the Geolocation API Work?

The API is available through the navigator.geolocation object in JavaScript.

It mainly has three methods:

  1. getCurrentPosition() → Get the current location once.
  2. watchPosition() → Track location continuously in real time.
  3. clearWatch() → Stop tracking location.

Getting User Location (Latitude & Longitude)

Here’s a simple example of getting the current position:

<button onclick="getLocation()">Get My 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 in this browser.";
  }
}

function showPosition(position) {
  document.getElementById("output").innerHTML =
    "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
}

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

Tracking User Location in Real Time

If you want to continuously monitor location (like in ride-tracking apps), use watchPosition().

let watchId = navigator.geolocation.watchPosition(pos => {
  console.log("Latitude:", pos.coords.latitude,
              "Longitude:", pos.coords.longitude);
});

Error Handling in Geolocation API

Errors can happen if:

  • The user denies permission
  • The device cannot detect location
  • The request times out

That’s why error callbacks are important (as shown in the example above).

Browser Support & Limitations

Supported by most modern browsers (Chrome, Edge, Firefox, Safari).

Requires HTTPS (except on localhost).

Accuracy depends on the device → GPS is more accurate than Wi-Fi or IP.

Security & Privacy Concerns

  • Browsers always ask permission before sharing location.
  • Never collect more data than needed.
  • Always explain why your app needs location.
  • Handle sensitive location data securely.

Real-World Use Cases

  1. Maps & Navigation – Google Maps, Apple Maps
  2. Food Delivery – Track orders in real-time
  3. Ride-Hailing – Ola, Uber live ride tracking
  4. Weather Apps – Show weather based on location
  5. Fitness Apps – Track running or cycling routes

Geolocation API vs Third-Party APIs

The built-in Geolocation API is simple and free, but limited.

For advanced features, developers often use:

  • Google Maps API – Rich maps, directions, geocoding
  • Mapbox API – Custom maps with styles
  • OpenStreetMap API – Free and open-source mapping

HTML5 Geolocation API Example – Get & Track User Location

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>HTML Geolocation API Example</title>
</head>
<body>
  <h2>🌍 HTML Geolocation API Demo</h2>
  <button onclick="getLocation()">Get My Location</button>
  <button onclick="startTracking()">Start Tracking</button>
  <button onclick="stopTracking()">Stop Tracking</button>

  <p id="output"></p>

  <script>
    let watchId;

    // 1. Get current location once
    function getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, showError);
      } else {
        document.getElementById("output").innerText = 
          "❌ Geolocation is not supported in this browser.";
      }
    }

    // Show latitude & longitude
    function showPosition(position) {
      document.getElementById("output").innerHTML =
        "✅ Current Location:<br>" +
        "Latitude: " + position.coords.latitude + "<br>" +
        "Longitude: " + position.coords.longitude;
    }

    // Handle errors
    function showError(error) {
      switch (error.code) {
        case error.PERMISSION_DENIED:
          alert("❌ User denied the location request.");
          break;
        case error.POSITION_UNAVAILABLE:
          alert("❌ Location info unavailable.");
          break;
        case error.TIMEOUT:
          alert("⏳ Location request timed out.");
          break;
        default:
          alert("⚠️ An unknown error occurred.");
      }
    }

    // 2. Track location continuously
    function startTracking() {
      if (navigator.geolocation) {
        watchId = navigator.geolocation.watchPosition((pos) => {
          document.getElementById("output").innerHTML =
            "📍 Tracking...<br>" +
            "Latitude: " + pos.coords.latitude + "<br>" +
            "Longitude: " + pos.coords.longitude;
        }, showError);
      }
    }

    // 3. Stop tracking
    function stopTracking() {
      if (watchId) {
        navigator.geolocation.clearWatch(watchId);
        document.getElementById("output").innerText = 
          "⏹️ Tracking stopped.";
      }
    }
  </script>
</body>
</html>

Output :

learn code with durgesh images

Article 0 of 0