Course contentsShow
← JavaScript
Lesson 1476 of 2,72332. JavaScript in the BrowserFree lesson

Geolocation API

Requesting user location with navigator.geolocation, handling permissions and position data.

Geolocation API

You'll learn how to request the user's physical location using the browser's Geolocation API and handle the permission flow.

What Is the Geolocation API?

The Geolocation API allows web applications to request a user's current geographic position through navigator.geolocation. Think of it like asking a friend "Where are you right now?"—but the browser asks on your behalf, and the user must explicitly grant permission first.

Requesting Location

The primary method is getCurrentPosition(), which takes two callbacks:

navigator.geolocation.getCurrentPosition(
  function(position) {
    // Success callback
    console.log('Latitude:', position.coords.latitude);
    console.log('Longitude:', position.coords.longitude);
    console.log('Accuracy:', position.coords.accuracy, 'meters');
  },
  function(error) {
    // Error callback
    console.log('Error code:', error.code);
    console.log('Error message:', error.message);
  }
);

Understanding the Flow

When you call getCurrentPosition(), the browser prompts the user for permission. Three outcomes are possible:

  1. Permission granted → Success callback runs with position data
  2. Permission denied → Error callback runs with code 1
  3. Position unavailable → Error callback runs with code 2

The position object contains coords.latitude, coords.longitude, coords.accuracy, and sometimes altitude, heading, and speed.

Common Error Codes

  • 1 (PERMISSION_DENIED): User blocked location access
  • 2 (POSITION_UNAVAILABLE): Location services failed
  • 3 (TIMEOUT): Request took too long

Optional Configuration

You can pass a third argument with options:

navigator.geolocation.getCurrentPosition(success, error, {
  timeout: 5000,        // Wait max 5 seconds
  maximumAge: 30000,    // Accept cached position up to 30s old
  enableHighAccuracy: true  // Request GPS-level precision
});

Key Takeaway: navigator.geolocation.getCurrentPosition() requests the user's location with explicit permission handling—always provide both success and error callbacks to manage the three possible outcomes.