JavaScript Geolocation API

The Geolocation API allows web applications to access the user's geographical location. For privacy reasons, the user must grant permission before their location can be accessed.

navigator.geolocation

The Geolocation API is accessed through the navigator.geolocation object. Before using it, you should check if geolocation is supported by the browser.

Checking Geolocation Support
// Check if geolocation is available
if ('geolocation' in navigator) {
  console.log('Geolocation is supported!');
} else {
  console.log('Geolocation is NOT supported.');
}

// The geolocation object provides:
// - getCurrentPosition() - one-time position
// - watchPosition() - continuous tracking
// - clearWatch() - stop tracking
console.log('Type: ' + typeof navigator.geolocation);

getCurrentPosition()

The getCurrentPosition() method gets the current position of the device. It takes a success callback, an optional error callback, and optional options.

Getting Current Position
// getCurrentPosition(success, error, options)

function showPosition(position) {
  console.log('Latitude: ' + position.coords.latitude);
  console.log('Longitude: ' + position.coords.longitude);
  console.log('Accuracy: ' + position.coords.accuracy + ' meters');
}

function showError(error) {
  switch(error.code) {
    case 1:
      console.log('User denied the request');
      break;
    case 2:
      console.log('Position unavailable');
      break;
    case 3:
      console.log('Request timed out');
      break;
  }
}

// In a real browser:
// navigator.geolocation.getCurrentPosition(showPosition, showError);

// Simulating a position
const mockPosition = {
  coords: { latitude: 40.7128, longitude: -74.0060, accuracy: 50 }
};
showPosition(mockPosition);

watchPosition()

The watchPosition() method continuously monitors the user's position. It returns a watch ID that can be used to stop tracking with clearWatch().

Watching Position Changes
// watchPosition returns a watch ID
// const watchId = navigator.geolocation.watchPosition(
//   function(position) {
//     console.log('Lat: ' + position.coords.latitude);
//     console.log('Lng: ' + position.coords.longitude);
//   },
//   function(error) {
//     console.log('Error: ' + error.message);
//   }
// );

// Stop watching
// navigator.geolocation.clearWatch(watchId);

// Simulating position updates
const positions = [
  { lat: 40.7128, lng: -74.0060 },
  { lat: 40.7130, lng: -74.0058 },
  { lat: 40.7135, lng: -74.0055 }
];

positions.forEach(function(pos, i) {
  console.log('Update ' + (i + 1) + ': ' + pos.lat + ', ' + pos.lng);
});

Position Object Properties

The position object returned by geolocation methods contains a coords object with latitude, longitude, and other properties.

PropertyDescriptionAlways Available
coords.latitudeLatitude in decimal degreesYes
coords.longitudeLongitude in decimal degreesYes
coords.accuracyAccuracy in metersYes
coords.altitudeAltitude in metersNo
coords.altitudeAccuracyAltitude accuracy in metersNo
coords.headingDirection of travel in degreesNo
coords.speedSpeed in meters per secondNo
timestampTime when position was acquiredYes
Using Position Properties
// Simulating a full position object
const position = {
  coords: {
    latitude: 51.5074,
    longitude: -0.1278,
    accuracy: 25,
    altitude: 11,
    altitudeAccuracy: 10,
    heading: 90,
    speed: 1.5
  },
  timestamp: Date.now()
};

console.log('Location: ' + position.coords.latitude + ', ' + position.coords.longitude);
console.log('Accuracy: ' + position.coords.accuracy + 'm');
console.log('Altitude: ' + position.coords.altitude + 'm');
console.log('Speed: ' + position.coords.speed + ' m/s');
console.log('Heading: ' + position.coords.heading + ' degrees');
console.log('Time: ' + new Date(position.timestamp).toLocaleString());

Error Handling and Permissions

Geolocation requests can fail for several reasons: the user denies permission, the position is unavailable, or the request times out. Always handle errors gracefully.

Options and Error Handling
// Geolocation options
const options = {
  enableHighAccuracy: true,  // Use GPS if available
  timeout: 5000,             // Max wait time (ms)
  maximumAge: 0              // No cached positions
};

console.log('High accuracy: ' + options.enableHighAccuracy);
console.log('Timeout: ' + options.timeout + 'ms');
console.log('Max age: ' + options.maximumAge);

// Error codes
const errors = {
  1: 'PERMISSION_DENIED',
  2: 'POSITION_UNAVAILABLE',
  3: 'TIMEOUT'
};

Object.keys(errors).forEach(function(code) {
  console.log('Error ' + code + ': ' + errors[code]);
});

// In production:
// navigator.geolocation.getCurrentPosition(
//   successCallback, errorCallback, options
// );
📝 Note: The Geolocation API requires HTTPS in modern browsers (except localhost). The user must explicitly grant permission, and they can revoke it at any time through browser settings. Always provide a fallback for users who deny location access.
Exercise:
What does navigator.geolocation.watchPosition() do?
Try it YourselfCtrl+Enter to run
Click Run to see the output here.