ReviseAlgo Logo

Browser APIs & Web APIs

Geolocation API

Master device location tracking in JavaScript. Learn the Geolocation API, requesting permissions, getCurrentPosition, and watchPosition.

Last Updated: July 15, 2026 10 min read

1. Introduction

The Geolocation API allows web applications to request a user's geographical location. It provides methods to retrieve the device's latitude, longitude, and accuracy details, or watch the location changes in real time.

2. Why It Matters

Adding location features (like finding nearby stores, auto-populating shipping addresses, or tracking shipping progress) improves user experience. Understanding how to check for permissions and handle coordinate streams is key to building location-aware apps.

3. Real-World Analogy

Think of a Hotel Front Desk Concierge:

  • getCurrentPosition (One-Time Question): You ask the concierge: "Where is the nearest subway station?" The concierge looks up your location once, gives you directions, and stops.
  • watchPosition (Constant Guide): You hire a tour guide who walks with you through the city. Every time you turn a corner or move to a new street, the guide updates you: "You are now approaching Exhibit A." The guide tracks your movement in real time until you tell them to stop.

4. The Geolocation API

The Geolocation API is accessed via the navigator.geolocation object, providing three main methods:

1. getCurrentPosition(success, error, options):

Requests the device's current location once. The browser displays a permission prompt to the user before retrieving the location.

2. watchPosition(success, error, options):

Registers a handler function that is called automatically whenever the device's location changes, returning a watch ID.

3. clearWatch(watchId):

Stops tracking location changes associated with the specified watch ID.

5. Practical Example

This script demonstrates checking if the Geolocation API is supported before requesting location data:

6. Common Mistakes

  • Not handling permission denials: If a user clicks "Block" on the browser's location prompt, the error callback triggers with code 1 (PERMISSION_DENIED). Always handle this case by displaying a helpful fallback message or input fields to manually enter location details.
  • Running Geolocation on HTTP connections: Geolocation is a powerful feature that requires a secure context. Modern browsers block Geolocation requests on non-secure (HTTP) connections, except on localhost.

7. Quick Quiz

Q1: Which method should you use to track device movement in real time?

A) getCurrentPosition()

B) watchPosition()

Answer: B — watchPosition() registers a callback handler that triggers automatically whenever the device's location changes.

8. Scenario-Based Challenge

The Location-Based Store Finder:

An application searches for nearby stores based on the user's location. If the geolocation request fails (due to denial or timeout), display a zipcode input form as a fallback. Write the controller logic for this fallback flow.

9. Debugging Exercise

Explain why this watch location tracker leaks memory, and how to fix it:

function trackUserTrip() {
  // Start tracking location
  navigator.geolocation.watchPosition((pos) => {
    console.log('Coordinates updated:', pos.coords.latitude);
  });
}

// User leaves page, but the watchPosition tracker is still active in the background! Why?

View Solution

Diagnosis: The watchPosition method registers a persistent background observer in the browser. If you don't save the watch ID and call clearWatch() when navigating away, the observer remains active in the background, consuming CPU resources and battery.

Fix: Save the watch ID, and call clearWatch() when the component unmounts or the user cancels tracking:

let tripWatchId = null;

function startTracking() { tripWatchId = navigator.geolocation.watchPosition((pos) => { console.log('Coords:', pos.coords.latitude); }); }

function stopTracking() { if (tripWatchId !== null) { navigator.geolocation.clearWatch(tripWatchId); // Clear observer tripWatchId = null; } }

10. Interview Questions

🟢 Q1: List the error codes returned by the Geolocation API and explain their causes.

Answer: The error callback receives an error object containing a code property:
1 (PERMISSION_DENIED): The user declined the location permission request.
2 (POSITION_UNAVAILABLE): The device could not retrieve location details (e.g. GPS signal lost or network offline).
3 (TIMEOUT): The request timed out before retrieving location coordinates (configured using the timeout option).

11. Production Considerations

  • Secure Context Required: The Geolocation API is a powerful feature that requires a secure context (HTTPS) in production. Browsers block location requests on non-secure (HTTP) pages, which can cause your code to fail silently if you don't handle the error case.