Lesson 9 of 11
Geolocation API (Deep Dive)
The Geolocation API can also track the user's position in real-time with watchPosition. Combine it with maps, distance calculations, and location-based features for powerful web applications.
Advanced Geolocation
- watchPosition() - Continuously track position (returns watch ID)
- clearWatch(id) - Stop tracking
- Distance calculation - Haversine formula to calculate distance between two coordinates
- Use cases - Store locators, delivery tracking, fitness apps, weather by location
- Privacy - Always explain WHY you need location. Provide 'enter manually' fallback
Advanced Geolocation Code
// Watch position (continuous tracking)
let watchId;
function startTracking() {
if (!navigator.geolocation) return;
watchId = navigator.geolocation.watchPosition(
(position) => {
const { latitude, longitude } = position.coords;
console.log(`๐ Updated: ${latitude.toFixed(4)}, ${longitude.toFixed(4)}`);
},
(error) => console.error("Tracking error:", error.message),
{ enableHighAccuracy: true }
);
}
function stopTracking() {
if (watchId) {
navigator.geolocation.clearWatch(watchId);
console.log("Tracking stopped");
}
}
// Calculate distance between two points (Haversine formula)
function getDistance(lat1, lon1, lat2, lon2) {
const R = 6371; // Earth's radius in km
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLon = (lon2 - lon1) * Math.PI / 180;
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon/2) * Math.sin(dLon/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
}
// Example: Mumbai to Delhi
const distance = getDistance(19.0760, 72.8777, 28.6139, 77.2090);
console.log(`Mumbai โ Delhi: ${distance.toFixed(0)} km`); // ~1153 km
console.log("Geolocation tracking demonstrated");Tip
Tip
Use navigator.onLine and the 'online'/'offline' events to detect network status. Show users a banner when they go offline and sync data when they come back online.
Geolocation API (Deep Dive) in JavaScript
Common Mistake
Warning
navigator.onLine only tells you if the device has a network connection, not if it can reach the internet. A connected WiFi without internet access still shows onLine = true. Test actual connectivity with a fetch request.
Practice Task
Note
Network detection: (1) Display online/offline status with event listeners. (2) Show device information (userAgent, language, platform). (3) Use URL API to parse and construct URLs dynamically.
Quick Quiz
Key Takeaways
- The Geolocation API can also track the user's position in real-time with watchPosition.
- watchPosition() - Continuously track position (returns watch ID)
- clearWatch(id) - Stop tracking
- Distance calculation - Haversine formula to calculate distance between two coordinates
Finished this lesson?