JavaScript Notes
Learn the JavaScript Geolocation API to get user latitude, longitude, and position accuracy. Covers permissions, getCurrentPosition, watchPosition, error handling, and interview Q&A.
The Geolocation API lets your web app ask the browser for the user's physical location — latitude, longitude, altitude, speed, and accuracy. It works via GPS on mobile, Wi-Fi triangulation, or IP lookup, depending on the device and settings.
💡 Requirements: Geolocation requires HTTPS (or localhost) and explicit user permission. The browser will show a permission prompt — your code must handle both approval and denial.
API Overview
Getting Location Once
"Latitude: 51.5074" "Longitude: -0.1278" "Accuracy: 15 metres" "Altitude: null" "Speed: null" "Timestamp: 2026-06-12T09:30:00.000Z"
Position Options
const options = {
enableHighAccuracy: true, // prefer GPS (slower, more battery) over Wi-Fi
timeout: 10000, // max ms to wait before calling error (default: Infinity)
maximumAge: 60000 // accept cached position up to 60 seconds old
};
navigator.geolocation.getCurrentPosition(onSuccess, onError, options);// With enableHighAccuracy: true — may get 3m accuracy instead of 50m // With timeout: 10000 — fires error callback if no fix within 10s // With maximumAge: 60000 — uses cached position if < 60s old (fast, saves battery)
Error Codes
"User denied location access" // code 1 "Location information unavailable" // code 2 "Location request timed out" // code 3
Watching Position (Continuous Updates)
"Watching with ID: 1" "Updated: 51.5074, -0.1278" "Updated: 51.5075, -0.1279" // as user moves "Stopped watching"
Practical: Show Location on a Map
"Open in Maps: https://www.google.com/maps?q=51.5074,-0.1278"
Coordinates Reference
| Property | Description | Unit |
|---|---|---|
latitude | North-South position | degrees (-90 to 90) |
longitude | East-West position | degrees (-180 to 180) |
accuracy | Radius of certainty | metres |
altitude | Height above sea level | metres (null if unavailable) |
altitudeAccuracy | Vertical accuracy | metres (null if unavailable) |
heading | Direction of travel | degrees (0=North, 90=East, null if not moving) |
speed | Speed of travel | metres/second (null if not moving) |
Permission Flow Diagram
When to Use Geolocation
- Store locator — find nearest shops / restaurants
- Delivery / ride-hailing apps — real-time driver/courier position
- Running / fitness trackers — record GPS route with
watchPosition - Weather apps — auto-detect location for local forecast
- Geotagging — attach coordinates to photos or social posts
Common Mistakes
- Not checking
"geolocation" in navigator— always feature-detect before calling the API. - Ignoring the error callback — PERMISSION_DENIED is common; apps must gracefully fall back (e.g., ask for manual city input).
- Using Geolocation on HTTP — it requires HTTPS in all modern browsers.
- Calling
getCurrentPositionin a loop — usewatchPositionfor continuous tracking andclearWatchto stop. - Not setting
timeout— in poor GPS conditions, the call hangs forever without a timeout. - Trusting coordinates without accuracy check — always check
coords.accuracyand warn users if it's large (e.g., >500m).
Interview Questions
Q1. What does navigator.geolocation.getCurrentPosition do?
It asynchronously requests the user's current geographic position. If the user grants permission, the success callback receives aGeolocationPositionobject withcoords(latitude, longitude, accuracy, etc.) and atimestamp.
Q2. What are the three Geolocation error codes?
1 =PERMISSION_DENIED(user blocked access), 2 =POSITION_UNAVAILABLE(device can't determine location), 3 =TIMEOUT(the request didn't complete within the allotted time).
Q3. What is the difference between getCurrentPosition and watchPosition?
getCurrentPositionfires the success callback once, then stops.watchPositionfires the callback every time the device's position changes, returning a watchId that can be passed toclearWatch()to stop.
Q4. Why does Geolocation require HTTPS?
Geolocation is a privacy-sensitive API. Browsers enforce HTTPS to prevent man-in-the-middle attacks from intercepting location data in transit.
Q5. What does enableHighAccuracy: true do?
It hints to the browser to use the most accurate method available (e.g., GPS instead of Wi-Fi/IP). This increases accuracy but uses more battery and takes longer to get a fix.
Q6. How do you handle the case where a user denies location access?
Catch the error in the error callback and check error.code === error.PERMISSION_DENIED. Then offer a fallback — such as a text input to enter a city name or postcode manually.Q7. What is maximumAge in Geolocation options?
It specifies (in milliseconds) the maximum age of a cached position that is acceptable. Setting maximumAge: 0 always requests a fresh fix. A higher value (e.g., 60000) can return a recent cached position quickly without waiting for a new GPS lock.Key Takeaways
- Geolocation requires HTTPS and explicit user permission.
- Always provide an error callback — PERMISSION_DENIED is common and must be handled gracefully.
- Use
getCurrentPositionfor a single fix; usewatchPosition+clearWatchfor continuous tracking. enableHighAccuracyimproves accuracy at the cost of battery and speed.- Check
coords.accuracy— IP-based location can be hundreds of kilometres off. - Feature-detect with
"geolocation" in navigatorbefore calling any geolocation methods.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Geolocation API in JavaScript — Get User Location Tutorial.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, browser, apis, geolocation
Related JavaScript Master Course Topics