The Geolocation API allows web applications to access the geographical location of a user's device, enabling location-based features like maps, local search, or tracking.

💡 How it works
The API obtains location data from the device using GPS, Wi-Fi, IP address, or other sensors. Users must grant permission before sharing location information with a web page.
Core Methods
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options)- Gets the current position once.navigator.geolocation.watchPosition(successCallback, errorCallback, options)- Continuously watches position changes.navigator.geolocation.clearWatch(watchId)- Stops watching position updates.
| Option | Description |
|---|---|
| enableHighAccuracy | Boolean to request more accurate position (may use more resources) |
| timeout | Maximum time (ms) to wait for location |
| maximumAge | Maximum cached position age (ms) allowed |
📌 Deep Dive: Getting Current Position
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, timeout: 5000 }
);
⚠️ Privacy and Permissions
Users must explicitly allow location access. Browsers usually prompt on first use. If denied, your error callback will handle it.
Handling Errors
The error callback receives a PositionError object with a code property:
1: Permission denied2: Position unavailable3: Timeout expired
Practical Use Case: Watching Position Changes
To track the user’s location continuously (e.g., for navigation), use watchPosition:
📌 Deep Dive: Watching Position
const watchId = navigator.geolocation.watchPosition(
pos => console.log(`Updated: ${pos.coords.latitude}, ${pos.coords.longitude}`),
err => console.error(err.message),
{ enableHighAccuracy: false, maximumAge: 10000 }
);
// To stop watching later
// navigator.geolocation.clearWatch(watchId);
💡 Browser Support
Most modern browsers support the Geolocation API on secure origins (HTTPS). Always check for availability using 'geolocation' in navigator.
Summary
- Use
getCurrentPosition()for one-time location. - Use
watchPosition()to track location updates. - Respect user privacy and handle permission errors gracefully.
- Configure options for accuracy, timeout, and caching.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which method is used to get the device's location just once?
Question 2 of 2
What happens if a user denies permission to access location?
Loading results...