The Geolocation API

· 6 min read · Updated March 7, 2026 · beginner
geolocation browser-api location navigator

The Geolocation API lets your web application access the user’s geographic location. This is powerful for location-aware features like showing nearby stores, personalizing content based on region, or tracking fitness activities. In this tutorial, you’ll learn how to request location data, handle permissions, and work with both one-time position requests and continuous tracking.

Checking for Geolocation Support

Before using the Geolocation API, check that the browser supports it and the user has granted permission:

if ('geolocation' in navigator) {
  console.log('Geolocation is supported!');
} else {
  console.log('Geolocation is not supported in this browser.');
}

The API is available through navigator.geolocation, which provides two main methods: getCurrentPosition() for a one-time location check and watchPosition() for continuous tracking.

Getting the Current Position

Use getCurrentPosition() to get the user’s location once. This is the most common way to use the Geolocation API. The method takes a success callback and optional error and options parameters:

navigator.geolocation.getCurrentPosition(
  (position) => {
    console.log('Latitude:', position.coords.latitude);
    console.log('Longitude:', position.coords.longitude);
    console.log('Accuracy:', position.coords.accuracy, 'meters');
  },
  (error) => {
    console.error('Error getting location:', error.message);
  },
  {
    enableHighAccuracy: true,
    timeout: 10000,
    maximumAge: 0
  }
);

The success callback receives a Position object with several useful properties:

  • latitude and longitude: The coordinates in decimal degrees
  • accuracy: Accuracy of the position in meters (lower is better)
  • altitude: Height above sea level in meters (may be null)
  • heading: Direction of movement in degrees (may be null)
  • speed: Speed in meters per second (may be null)

The error callback receives a PositionError with a code indicating what went wrong: PERMISSION_DENIED, POSITION_UNAVAILABLE, or TIMEOUT.

Understanding Position Options

The third parameter to getCurrentPosition() is an Options object that controls how the location is retrieved:

  • enableHighAccuracy: Set to true for GPS-level accuracy (default false). This is slower and uses more battery, but gives you the best possible position. Useful for mapping applications where meter-level precision matters.
  • timeout: Maximum time in milliseconds to wait for a result (default Infinity). If the timeout expires before a position is obtained, the error callback is called with a TIMEOUT error.
  • maximumAge: Maximum age in milliseconds of a cached position to accept (default 0). Set this to a positive value to skip requesting a new position and use a recent cached result instead. This is much faster and saves battery.

For most web apps, the defaults work fine. Enable high accuracy only when you genuinely need precise location:

// Quick location for regional content
// Uses cached position if available, falls back quickly
navigator.geolocation.getCurrentPosition((pos) => {
  console.log(pos.coords.latitude, pos.coords.longitude);
});

// Precise location for mapping
// Takes longer but more accurate
navigator.geolocation.getCurrentPosition(
  (pos) => console.log(pos.coords),
  (err) => console.error(err),
  { enableHighAccuracy: true, timeout: 30000 }
);

// Use cached position if less than 5 minutes old
navigator.geolocation.getCurrentPosition(
  (pos) => console.log('Cached:', pos.coords),
  (err) => console.error(err),
  { maximumAge: 300000 }
);

Watching Position Changes

Use watchPosition() to track the user’s location as they move. This is ideal for real-time applications like fitness trackers, delivery tracking, or navigation apps. The method returns a watch ID that you use to identify and stop the watch:

const watchId = navigator.geolocation.watchPosition(
  (position) => {
    console.log('New position:', position.coords.latitude, position.coords.longitude);
    console.log('Speed:', position.coords.speed, 'm/s');
  },
  (error) => {
    console.error('Watch error:', error.message);
  },
  { enableHighAccuracy: true }
);

// Stop watching when done (e.g., user closes the map)
function stopTracking() {
  navigator.geolocation.clearWatch(watchId);
  console.log('Location tracking stopped');
}

This returns a watch ID that you use with clearWatch() to stop tracking. The watch continues in the background while the user navigates, so always provide a clear way for users to stop tracking. This is not only good UX—it’s often a legal requirement in many jurisdictions for privacy compliance.

Handling Errors

The error callback receives a PositionError with three possible codes:

navigator.geolocation.getCurrentPosition(
  success,
  (error) => {
    switch (error.code) {
      case error.PERMISSION_DENIED:
        console.log('User denied location access');
        break;
      case error.POSITION_UNAVAILABLE:
        console.log('Location unavailable');
        break;
      case error.TIMEOUT:
        console.log('Location request timed out');
        break;
    }
  }
);

Always handle these errors gracefully. If permission is denied, fall back to IP-based geolocation or ask the user to enable location access.

Privacy Considerations

The Geolocation API is powerful but also sensitive—users trust you with their physical location. Mishandling this data can lead to serious privacy violations and legal issues. Always follow these best practices:

Request location only when needed. Don’t ask for location on page load. Wait until the user explicitly interacts with a feature that requires it, like clicking a “Find nearby stores” button.

Explain why you need location data. Users are more likely to grant permission when they understand how it’ll benefit them. A clear explanation like “We need your location to show you nearby restaurants” is far more effective than a generic permission prompt.

Provide a clear way to opt out. Once you’ve obtained location access, make it easy for users to revoke it. Include a prominent “Stop tracking my location” option in your UI.

Never track location in the background without explicit consent. Background location tracking raises significant privacy concerns. Only use watchPosition() when the user has a clear expectation that tracking is active.

Store location data securely. If you server-side store user locations, encrypt them and implement appropriate access controls. Consider data minimization—don’t keep location data longer than necessary.

// Ask permission clearly with context
async function requestLocation() {
  try {
    // First check the permission state
    const permission = await navigator.permissions.query({ name: 'geolocation' });
    
    if (permission.state === 'denied') {
      console.log('Please enable location access in your browser settings');
      return null;
    }
    
    if (permission.state === 'prompt') {
      console.log('Permission will be requested...');
    }
    
    // Now request the position
    return new Promise((resolve, reject) => {
      navigator.geolocation.getCurrentPosition(resolve, reject);
    });
  } catch (e) {
    // Fallback for older browsers that don't support permissions API
    return new Promise((resolve, reject) => {
      navigator.geolocation.getCurrentPosition(resolve, reject);
    });
  }
}

Summary

The Geolocation API provides a powerful way to build location-aware web applications. Here’s what you learned:

  • Use getCurrentPosition() for one-time location checks—perfect for personalized content based on the user’s region
  • Use watchPosition() for continuous tracking—ideal for fitness apps, delivery tracking, or navigation
  • Always handle errors gracefully with proper error codes
  • Respect user privacy by requesting location only when needed and providing clear opt-out options

The Geolocation API works in all modern browsers and is one of the most widely adopted web APIs. With this knowledge, you can build sophisticated location-aware features that delight users while respecting their privacy.

Next Steps

Now that you know the basics of the Geolocation API, continue building location-aware features:

  • Explore the Notifications API to engage users with timely alerts when they arrive at a destination
  • Learn about the Clipboard API for copying and pasting location data
  • Try combining Geolocation with the Fetch API to send location data to a server for backend processing

With these tools, you can create truly intelligent applications that adapt to where your users are.