Geolocation & Web Workers
Location-aware apps with explicit permission, and background threads for heavy computation.
HTML5 Geolocation API
Geolocation lets a web application access the user's physical location — with explicit permission.
// Check if geolocation is supported
if ("geolocation" in navigator) {
// Get current position (one-time)
navigator.geolocation.getCurrentPosition(
(position) => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
const acc = position.coords.accuracy; // meters
console.log(`Lat: ${lat}, Lon: ${lon}, Accuracy: ${acc}m`);
},
(error) => console.error("Error: ", error.message),
{ enableHighAccuracy: true, timeout: 5000 }
);
// Watch position changes (continuous)
const watchId = navigator.geolocation.watchPosition(callback);
// Stop watching
navigator.geolocation.clearWatch(watchId);
}
Methods
getCurrentPosition()— retrieves the position oncewatchPosition()— continuously monitors positionclearWatch(id)— stops watching
Location sources
IP address, Wi-Fi triangulation, cell tower data and GPS (device hardware).
Geolocation: Privacy & Best Practices
- User consent required — the browser always prompts before sharing location; no data is transmitted without explicit permission.
- Accuracy varies — IP address is city-level (~10 m), Wi-Fi is more precise, GPS is most accurate.
- HTTPS required — modern browsers block geolocation over HTTP. Always deploy with TLS/HTTPS.
- Respect the user — cache location when appropriate and don't call
watchPosition()unnecessarily (it drains battery).
Web Workers — Background Threads
JavaScript is single-threaded by design. Web Workers add true background execution so heavy tasks don't freeze the UI.
// main.js
const worker = new Worker("worker.js");
worker.postMessage({ data: bigArray });
worker.onmessage = (e) => {
console.log("Result:", e.data);
};
// worker.js
self.onmessage = (e) => {
const result = heavyComputation(e.data);
self.postMessage(result);
};
- CPU-intensive tasks don't freeze the UI.
- Multiple workers can run in parallel.
- Communicate via
postMessage()/onmessage. - No access to the DOM (runs in a separate scope).
Activity — complete the code
Complete the code correctly to mark this lesson as complete automatically.
Complete the Geolocation call and the Web Worker.
if ("geolocation" in navigator) {navigator.geolocation.((position) => {console.log(position.coords.latitude);});}// Background threadconst worker = new ("worker.js");worker.({ data: bigArray });