Geolocation API

The Geolocation API allows web applications to access the geographical location of a user's device, enabling location-based features like maps, local search, or tracking.

Illustration of Geolocation API
Illustration of Geolocation API

💡 How it works

The API obtains location data from the device using GPS, Wi-Fi, IP address, or other sensors. Users must grant permission before sharing location information with a web page.

Core Methods

  • navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options) - Gets the current position once.
  • navigator.geolocation.watchPosition(successCallback, errorCallback, options) - Continuously watches position changes.
  • navigator.geolocation.clearWatch(watchId) - Stops watching position updates.
Geolocation Options
OptionDescription
enableHighAccuracyBoolean to request more accurate position (may use more resources)
timeoutMaximum time (ms) to wait for location
maximumAgeMaximum cached position age (ms) allowed

📌 Deep Dive: Getting Current Position

JAVASCRIPT
navigator.geolocation.getCurrentPosition(
  position => {
    const { latitude, longitude } = position.coords;
    console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
  },
  error => {
    console.error('Error getting location:', error.message);
  },
  { enableHighAccuracy: true, timeout: 5000 }
);
Output
Latitude: 37.7749, Longitude: -122.4194 (example)

⚠️ Privacy and Permissions

Users must explicitly allow location access. Browsers usually prompt on first use. If denied, your error callback will handle it.

Handling Errors

The error callback receives a PositionError object with a code property:

  • 1: Permission denied
  • 2: Position unavailable
  • 3: Timeout expired

Practical Use Case: Watching Position Changes

To track the user’s location continuously (e.g., for navigation), use watchPosition:

📌 Deep Dive: Watching Position

JAVASCRIPT
const watchId = navigator.geolocation.watchPosition(
  pos => console.log(`Updated: ${pos.coords.latitude}, ${pos.coords.longitude}`),
  err => console.error(err.message),
  { enableHighAccuracy: false, maximumAge: 10000 }
);

// To stop watching later
// navigator.geolocation.clearWatch(watchId);

💡 Browser Support

Most modern browsers support the Geolocation API on secure origins (HTTPS). Always check for availability using 'geolocation' in navigator.

Summary

  • Use getCurrentPosition() for one-time location.
  • Use watchPosition() to track location updates.
  • Respect user privacy and handle permission errors gracefully.
  • Configure options for accuracy, timeout, and caching.