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.
// 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.
// 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().
// 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.
| Property | Description | Always Available |
|---|---|---|
| coords.latitude | Latitude in decimal degrees | Yes |
| coords.longitude | Longitude in decimal degrees | Yes |
| coords.accuracy | Accuracy in meters | Yes |
| coords.altitude | Altitude in meters | No |
| coords.altitudeAccuracy | Altitude accuracy in meters | No |
| coords.heading | Direction of travel in degrees | No |
| coords.speed | Speed in meters per second | No |
| timestamp | Time when position was acquired | Yes |
// 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.
// 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
// );