The Geolocation API provides a way for web applications to retrieve the geographic location of the user's device. This allows for location-aware services such as mapping, navigation, and location-based content.
The Geolocation API is accessed via the global navigator.geolocation object. It allows you to request the user's current position, either once or by watching for changes to their position.
To get the user's current location, you can use the getCurrentPosition() method. This method asynchronously retrieves the device's location. It takes up to three arguments:
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options)The success callback function receives a single argument: a GeolocationPosition object. This object contains the position information.
Key properties of GeolocationPosition:
coords: A GeolocationCoordinates object containing the actual location data.timestamp: A DOMTimeStamp indicating when the geolocation was acquired.GeolocationCoordinates Propertieslatitude: The latitude in decimal degrees.longitude: The longitude in decimal degrees.accuracy: The accuracy of the latitude and longitude properties, in meters.altitude: The altitude in meters above the WGS84 ellipsoid. Can be null.altitudeAccuracy: The accuracy of the altitude property, in meters. Can be null.heading: The direction that the device is moving, specified in degrees, with 0° being true north. Can be null.speed: The current ground speed of the device, specified in meters per second. Can be null.The error callback function receives a single argument: a GeolocationPositionError object.
Key properties of GeolocationPositionError:
code: An error code. Possible values are:
1 (PERMISSION_DENIED)2 (POSITION_UNAVAILABLE)3 (TIMEOUT)4 (UNKNOWN_ERROR)message: A human-readable string describing the error.The options object can include the following properties:
enableHighAccuracy: A boolean. If true, the device attempts to retrieve a more accurate location (e.g., using GPS). Defaults to false.timeout: A number representing the maximum time (in milliseconds) that the device can take to return a valid location. Defaults to infinity.maximumAge: A number representing the maximum age (in milliseconds) of a cached position that is acceptable. Defaults to 0.
function showPosition(position) {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
document.getElementById("location-info").innerHTML = `
Latitude: ${lat}
Longitude: ${lon}
Accuracy: ${position.coords.accuracy} meters
`;
}
function showError(error) {
let message = "An unknown error occurred.";
switch (error.code) {
case error.PERMISSION_DENIED:
message = "User denied the request for Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
message = "Location information is unavailable.";
break;
case error.TIMEOUT:
message = "The request to get user location timed out.";
break;
case error.UNKNOWN_ERROR:
message = "An unknown error occurred.";
break;
}
document.getElementById("location-info").innerHTML = `Error: ${message}
`;
}
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError, {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
});
} else {
document.getElementById("location-info").innerHTML = "Geolocation is not supported by this browser.
";
}
}
Click the button to get your location.
The watchPosition() method is similar to getCurrentPosition(), but it registers a handler function that is called automatically each time the device's location changes.
This is useful for applications that need to track a user's movement over time.
navigator.geolocation.watchPosition(successCallback, errorCallback, options)The callbacks and options are the same as for getCurrentPosition(). To stop watching, you need to call clearWatch() with the ID returned by watchPosition().
let watchId = null;
function showWatchingPosition(position) {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
document.getElementById("watch-location-info").innerHTML = `
Latitude: ${lat}
Longitude: ${lon}
Accuracy: ${position.coords.accuracy} meters
`;
}
function showWatchingError(error) {
let message = "An unknown error occurred.";
switch (error.code) {
case error.PERMISSION_DENIED:
message = "User denied the request for Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
message = "Location information is unavailable.";
break;
case error.TIMEOUT:
message = "The request to get user location timed out.";
break;
case error.UNKNOWN_ERROR:
message = "An unknown error occurred.";
break;
}
document.getElementById("watch-location-info").innerHTML = `Error: ${message}
`;
}
function startWatching() {
if (navigator.geolocation) {
if (watchId === null) {
watchId = navigator.geolocation.watchPosition(showWatchingPosition, showWatchingError, {
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 5000
});
document.getElementById("start-watch-btn").textContent = "Stop Watching";
document.getElementById("watch-location-info").innerHTML = "Watching for location changes...
";
} else {
stopWatching();
}
} else {
document.getElementById("watch-location-info").innerHTML = "Geolocation is not supported by this browser.
";
}
}
function stopWatching() {
if (watchId !== null) {
navigator.geolocation.clearWatch(watchId);
watchId = null;
document.getElementById("start-watch-btn").textContent = "Start Watching";
document.getElementById("watch-location-info").innerHTML = "Location watching stopped.
";
}
}
Click the button to start watching your location.
The Geolocation API requires user permission before it can access their location. Browsers will typically display a prompt to the user asking for permission. It's important to inform users why you need their location and how you will use it to build trust.
Always handle location data responsibly and consider anonymizing or aggregating data where possible.
The Geolocation API is widely supported by modern web browsers. However, always check specific browser documentation for the latest compatibility information.
Supported browsers include Chrome, Firefox, Safari, Edge, and Opera.