The Geolocation API is a key HTML5 feature that provides access to location data (latitude and longitude) derived from the user’s device, typically using GPS, Wi-Fi, or cellular network data.
1. Security and Permissions
The most important rule of the Geolocation API is that it is strictly controlled by the browser for user privacy.
- Secure Context: Geolocation only works on pages served over a secure context (HTTPS), except when running locally (e.g., via Live Server).
- User Consent: The browser must explicitly ask the user for permission the first time a site attempts to access their location. If the user denies permission, the API call will fail.
2. Accessing the Geolocation Object
The Geolocation API is accessed through the navigator.geolocation object, which is available in the global JavaScript navigator object.
The main method used to retrieve the location is getCurrentPosition().
// Check if the browser supports Geolocation
if (navigator.geolocation) {
// Attempt to get the current position
navigator.geolocation.getCurrentPosition(successFunction, errorFunction, options);
} else {
// Geolocation is not supported by this browser
alert("Geolocation is not supported by this browser.");
}
3. The getCurrentPosition() Method
This method takes up to three arguments:
successFunction(Required): A callback function that runs if the position is successfully retrieved. It receives aPositionobject as its argument.errorFunction(Optional): A callback function that runs if an error occurs (e.g., permission denied, GPS timeout). It receives aPositionErrorobject.options(Optional): An object used to configure the request (e.g., timeout, accuracy).
A. Success Callback
The success function receives a Position object, which contains a nested coords object holding the coordinates:
function successFunction(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const accuracy = position.coords.accuracy; // accuracy in meters
// Example: Display the coordinates in an HTML element
document.getElementById('location-data').innerHTML =
`Latitude: ${latitude}, Longitude: ${longitude}`;
}
B. Error Callback
The error function helps debug why the location retrieval failed:
function errorFunction(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.");
break;
}
}
4. Optional Configuration (options)1
You can opt2imize the request using optional parameters:
| Option | Type | Description |
enableHighAccuracy | Boolean | If true, the device tries to provide a better location fix (slower, uses more battery). Default is false. |
timeout | Number (ms) | The maximum time allowed for the request to return a position. |
maximumAge | Number (ms) | The maximum age (in milliseconds) of a possible cached position that the browser can use. 0 means get a fresh position. |
const options = {
enableHighAccuracy: true,
timeout: 5000, // 5 seconds
maximumAge: 0 // No cached data
};
navigator.geolocation.getCurrentPosition(successFunction, errorFunction, options);
5. Tracking the User (watchPosition)
If you need continuous updates as the user moves (e.g., for a navigation app), you would use the watchPosition() method instead of getCurrentPosition(). It works identically but calls the success/error functions repeatedly whenever the location changes.
