Geolocation API Support and Permission Handling
Detect Geolocation API support for accessing the user's geographic location. Covers permission flow, accuracy options, and privacy considerations.
Sensors
Detailed Explanation
Geolocation API Detection
The Geolocation API provides access to the user's geographic position, enabling location-aware web applications. It requires explicit user permission and works only on secure origins (HTTPS).
Detection
const hasGeolocation = 'geolocation' in navigator;
Getting Position
function getCurrentPosition(options = {}) {
return new Promise((resolve, reject) => {
if (!navigator.geolocation) {
reject(new Error('Geolocation not supported'));
return;
}
navigator.geolocation.getCurrentPosition(
resolve,
reject,
{
enableHighAccuracy: options.highAccuracy || false,
timeout: options.timeout || 10000,
maximumAge: options.maxAge || 0,
}
);
});
}
// Usage
const pos = await getCurrentPosition({ highAccuracy: true });
console.log(pos.coords.latitude, pos.coords.longitude);
Watching Position
const watchId = navigator.geolocation.watchPosition(
(position) => {
updateMap(position.coords);
},
(error) => {
console.error('Watch error:', error.code);
},
{ enableHighAccuracy: true }
);
// Stop watching
navigator.geolocation.clearWatch(watchId);
Position Object
| Property | Description |
|---|---|
latitude |
Decimal degrees |
longitude |
Decimal degrees |
accuracy |
Meters (radius of confidence) |
altitude |
Meters above sea level (optional) |
altitudeAccuracy |
Meters (optional) |
heading |
Degrees from north (optional) |
speed |
Meters per second (optional) |
Error Codes
| Code | Constant | Meaning |
|---|---|---|
| 1 | PERMISSION_DENIED | User denied permission |
| 2 | POSITION_UNAVAILABLE | Location unavailable |
| 3 | TIMEOUT | Request timed out |
Privacy Considerations
- Always explain why you need location data before requesting it
- Use the minimum accuracy level needed for your use case
- Do not store or transmit location data without user consent
- Provide manual location input as an alternative
Use Case
Used for mapping applications, local business search, delivery tracking, weather apps, ride-sharing services, and location-based reminders. Important for any application that needs to show relevant content based on the user's physical location.