MyInternships.in

HTML APIs

HTML Geolocation

The HTML5 Geolocation API lets a web page ask the browser for the user's geographic location - latitude, longitude and accuracy - always with the user's explicit permission and only over a secure HTTPS connection.


What is the Geolocation API and why use it?

The Geolocation API is a browser API exposed through the global navigator.geolocation object. It gives web applications access to the device's physical location using signals such as GPS, Wi-Fi, cell towers and IP address. It is not HTML markup - it is a JavaScript API standardised by the W3C that ships in every modern browser.

You reach for it whenever the page needs to know where the user is: showing nearby stores on a map, auto-filling a delivery address, giving local weather, finding the closest branch, or tagging a photo with a location. Because location is sensitive personal data, the browser never hands it over silently - it always asks the user first.

Syntax

The API has three methods. getCurrentPosition() reads the location once; watchPosition() gets repeated updates; clearWatch() stops watching. Each read method takes a success callback, an optional error callback, and an optional options object.

The three methods at a glance
navigator.geolocation.getCurrentPosition(success, error, options);

const id = navigator.geolocation.watchPosition(success, error, options);
navigator.geolocation.clearWatch(id);

// options object
const options = {
  enableHighAccuracy: true, // request GPS-level precision
  timeout: 10000,           // max ms to wait for a fix
  maximumAge: 0             // do not use a cached position
};

Example: get the user's current position

Copy this complete page into the editor and click the button. On a real HTTPS site the browser shows a permission prompt; if you allow it, the coordinates appear. Inside the sandboxed preview the prompt may be blocked - see the note below.

Runnable: show my location on a button click
Example
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Geolocation demo</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 24px; }
    button { padding: 10px 18px; font-size: 15px; cursor: pointer; }
    #output { margin-top: 16px; padding: 14px; background: #eef2ff;
              border-radius: 8px; min-height: 24px; }
  </style>
</head>
<body>
  <h3>Where am I?</h3>
  <button id="locate">Show my location</button>
  <div id="output">Your location will appear here.</div>

  <script>
    const output = document.getElementById("output");

    document.getElementById("locate").addEventListener("click", () => {
      if (!("geolocation" in navigator)) {
        output.textContent = "Geolocation is not supported by this browser.";
        return;
      }
      output.textContent = "Requesting your location...";

      navigator.geolocation.getCurrentPosition(
        (position) => {
          const c = position.coords;
          output.innerHTML =
            "Latitude: <b>" + c.latitude.toFixed(5) + "</b><br>" +
            "Longitude: <b>" + c.longitude.toFixed(5) + "</b><br>" +
            "Accuracy: ~" + Math.round(c.accuracy) + " metres";
        },
        (error) => {
          output.textContent = "Error (" + error.code + "): " + error.message;
        },
        { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 }
      );
    });
  </script>
</body>
</html>

The success callback receives a GeolocationPosition object. Its coords property holds latitude, longitude and accuracy (in metres), plus altitude, altitudeAccuracy, heading and speed where the hardware supports them. position.timestamp records when the reading was taken.

More examples: tracking movement and reverse geocoding

For live navigation you want continuous updates. watchPosition() fires the callback every time the position changes and returns a numeric ID you pass to clearWatch() to stop and save battery.

Track movement, then stop
const watchId = navigator.geolocation.watchPosition(
  (position) => {
    console.log("Moved to:", position.coords.latitude, position.coords.longitude);
  },
  (error) => console.warn("Watch error:", error.message),
  { enableHighAccuracy: true, maximumAge: 5000 }
);

// Later, when you no longer need updates:
navigator.geolocation.clearWatch(watchId);

The raw coordinates are numbers. To turn them into a human-readable address (a street, city, country) you send them to a reverse-geocoding service - the Geolocation API itself does not provide place names.

Key methods, objects and error codes

MemberTypePurpose
getCurrentPosition(success, error?, options?)MethodRead the location a single time
watchPosition(success, error?, options?)MethodRepeated updates as the device moves; returns a watch ID
clearWatch(id)MethodStop a watch started by watchPosition()
position.coordsGeolocationCoordinateslatitude, longitude, accuracy, altitude, heading, speed
position.timestampNumber (ms)When the reading was taken
error.code = 1PERMISSION_DENIEDThe user blocked the request
error.code = 2POSITION_UNAVAILABLEThe device could not get a fix
error.code = 3TIMEOUTTimed out before a fix was found
⚠️

HTTPS only: the Geolocation API works only in a secure context. The page must be served over HTTPS (localhost counts as secure for development). On plain http:// pages, every navigator.geolocation call is blocked in modern browsers.

ℹ️

Permission: the first call triggers a browser prompt to Allow or Block location. If the user denies it, the error callback gets code 1 (PERMISSION_DENIED). The 'Try it' editor runs inside a sandboxed iframe, so the permission prompt may be blocked and you might see an error even on HTTPS - the very same code works normally when the page is opened directly on a real HTTPS site.

Key Takeaways

  • The Geolocation API lives on navigator.geolocation - it is JavaScript, not markup.
  • getCurrentPosition() reads location once; watchPosition() streams updates; clearWatch() stops them.
  • Read data from position.coords (latitude, longitude, accuracy) and position.timestamp.
  • It requires HTTPS and always asks the user for permission - handle the error callback for a denied prompt.
  • Turning coordinates into an address needs a separate reverse-geocoding service.

Related HTML Topics

Keep learning with these closely related tutorials.

Ready to use your HTML skills?

Find web development internships and fresher jobs across India.

Browse Web Dev Internships