You will learn how to request the user's current location in JavaScript using the Geolocation API, handle permission and errors, and read coordinates safely.
What it is
The Geolocation API is a browser interface that lets a web page ask the user for permission to read their approximate physical location. The main object is navigator.geolocation. A successful request returns a GeolocationPosition object, whose coords property contains values such as latitude, longitude, and accuracy. Related terms include permission prompt, secure context, watch position, and position error.
Why it matters
- It enables location-aware features such as nearby stores, weather, or map centering.
- It gives more accurate results than IP-based location when the user agrees.
- It respects privacy by requiring explicit permission in most browsers.
- It supports both one-time checks and continuous tracking.
Syntax or steps
The smallest useful pattern is navigator.geolocation.getCurrentPosition(success, error, options). The success callback receives a position object. The error callback receives a GeolocationPositionError. The optional options object can include enableHighAccuracy, timeout, and maximumAge. The page must run in a secure context, usually HTTPS or localhost.
Example
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function showPosition(position) {
const { latitude, longitude, accuracy } = position.coords;
console.log(`Lat: ${latitude}, Lon: ${longitude}, Accuracy: ${accuracy} m`);
}
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
console.warn("User denied location permission.");
break;
case error.POSITION_UNAVAILABLE:
console.warn("Location information is unavailable.");
break;
case error.TIMEOUT:
console.warn("Location request timed out.");
break;
default:
console.warn("Unknown error:", error.message);
}
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError, options);
} else {
console.warn("Geolocation is not supported.");
}
The options object asks for high accuracy, stops after five seconds, and avoids cached positions. showPosition reads the coordinates. showError explains common failures. The final block checks support before calling the API.
Common mistakes
- Assuming permission is granted. Always provide an error callback and handle denial.
- Testing on HTTP. Use HTTPS or localhost, or the API may be unavailable.
- Ignoring accuracy.
accuracyis in meters; do not treat the coordinates as exact. - Tracking forever. If using
watchPosition, callclearWatchwhen tracking is no longer needed.
When to use it
| Need | Use | Why |
|---|---|---|
| One-time location | getCurrentPosition | Simple and stops after one result. |
| Live movement | watchPosition | Receives updates as the user moves. |
| No permission or fallback | IP geolocation service | Less accurate but does not require browser permission. |
Practice
Guided exercise: Add a button that calls getCurrentPosition and displays latitude and longitude in the page. Expected output: Lat: 37.7749, Lon: -122.4194.
Challenge: Use watchPosition to log updates, then stop tracking after ten seconds.
Hint: Store the watch ID returned by watchPosition and pass it to clearWatch.
Quick check
What does accuracy mean in position.coords?
It is the radius, in meters, within which the browser believes the user is located.
Summary
The Geolocation API provides browser-based location data only after the user grants permission. Use getCurrentPosition for one-time checks, handle errors carefully, and treat coordinates as approximate.