Web Geolocation API
The Geolocation API allows web applications to access the user’s geographic location through the browser. This includes latitude, longitude, altitude, speed, and accuracy data. It is part of the Browser Object Model (BOM) and is accessed via navigator.geolocation
.
Note: Browsers will ask users for permission before sharing location data. Always handle permission denial or errors gracefully.
Key Features of the Geolocation API
- Access user location in latitude and longitude.
- Provides optional details like altitude, speed, heading, and accuracy.
- Supports single retrieval (
getCurrentPosition
) and continuous tracking (watchPosition
). - Returns a Position object containing coordinates and a timestamp.
- Works across most modern browsers and mobile devices.
getCurrentPosition() – Get Location Once
getCurrentPosition
retrieves the user’s current location one time.
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude } = position.coords;
console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
},
(error) => {
console.error("Error getting location:", error.message);
},
{ enableHighAccuracy: true }
);
Parameters:
successCallback
: Function executed when location is successfully obtained.errorCallback
(optional): Function executed if an error occurs.options
(optional): Object to customize behavior:enableHighAccuracy
:true
for precise location.timeout
: Maximum time (ms) to wait.maximumAge
: Maximum cached position age (ms).
watchPosition() – Continuous Location Updates
watchPosition
continuously monitors the user’s location and updates whenever it changes.
const watchId = navigator.geolocation.watchPosition(
(position) => {
console.log(`Updated position: ${position.coords.latitude}, ${position.coords.longitude}`);
},
(error) => console.error(error),
{ enableHighAccuracy: true, maximumAge: 0 }
);
// To stop watching
navigator.geolocation.clearWatch(watchId);
Position Object
The Position object returned in the success callback contains:
Property | Description |
---|---|
position.coords.latitude | Latitude in decimal degrees |
position.coords.longitude | Longitude in decimal degrees |
position.coords.altitude | Altitude in meters (if available) |
position.coords.accuracy | Accuracy of latitude & longitude in meters |
position.coords.altitudeAccuracy | Accuracy of altitude in meters |
position.coords.heading | Direction of travel in degrees (if moving) |
position.coords.speed | Speed in meters/second (if moving) |
position.timestamp | Time at which the position was recorded |
Error Handling
If the browser cannot retrieve location, the errorCallback receives a PositionError
object:
Code | Meaning |
---|---|
1 | PERMISSION_DENIED |
2 | POSITION_UNAVAILABLE |
3 | TIMEOUT |
Example:
navigator.geolocation.getCurrentPosition(
() => console.log("Location obtained"),
(error) => {
switch(error.code) {
case 1: console.log("Permission denied"); break;
case 2: console.log("Position unavailable"); break;
case 3: console.log("Timeout"); break;
}
}
);
Practical Example – Display Location on Page
<p id="location">Fetching location...</p>
<script>
const locEl = document.getElementById("location");
navigator.geolocation.getCurrentPosition(
(pos) => {
const { latitude, longitude } = pos.coords;
locEl.textContent = `Latitude: ${latitude}, Longitude: ${longitude}`;
},
(err) => {
locEl.textContent = "Unable to get location.";
console.error(err);
}
);
</script>