Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
The Geolocation API allows you to access the user's geographical position. It provides latitude, longitude, altitude, speed, and more. The API requires user permission for privacy reasons.
User must explicitly grant permission before location access
Uses GPS, WiFi, IP address, cell towers for location
Can continuously track user's position as they move
// Check if Geolocation is supported
if ('geolocation' in navigator) {
// Get current position
navigator.geolocation.getCurrentPosition(
// Success callback
(position) => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
const accuracy = position.coords.accuracy;
console.log(`Latitude: ${lat}`);
console.log(`Longitude: ${lon}`);
console.log(`Accuracy: ${accuracy} meters`);
// Optional properties (may not be available)
if (position.coords.altitude !== null) {
console.log(`Altitude: ${position.coords.altitude}m`);
}
if (position.coords.speed !== null) {
console.log(`Speed: ${position.coords.speed} m/s`);
}
},
// Error callback
(error) => {
switch(error.code) {
case error.PERMISSION_DENIED:
console.error('User denied geolocation');
break;
case error.POSITION_UNAVAILABLE:
console.error('Position unavailable');
break;
case error.TIMEOUT:
console.error('Request timeout');
break;
default:
console.error('Unknown error');
}
},
// Options
{
enableHighAccuracy: true, // Use GPS if available
timeout: 5000, // Wait max 5 seconds
maximumAge: 0 // Don't use cached position
}
);
} else {
console.error('Geolocation not supported');
}| Property | Description | Always Available |
|---|---|---|
coords.latitude | Latitude in decimal degrees | Yes |
coords.longitude | Longitude in decimal degrees | Yes |
coords.accuracy | Accuracy in meters | Yes |
coords.altitude | Height above sea level (meters) | No |
coords.altitudeAccuracy | Altitude accuracy in meters | No |
coords.heading | Direction of travel (degrees, 0=North) | No |
coords.speed | Speed in meters per second | No |
timestamp | When position was acquired | Yes |
// Start watching position
const watchId = navigator.geolocation.watchPosition(
// Success callback (called repeatedly)
(position) => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
console.log(`New position: ${lat}, ${lon}`);
// Update map marker, calculate distance, etc.
updateMapMarker(lat, lon);
},
// Error callback
(error) => {
console.error('Watch error:', error.message);
},
// Options
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
}
);
// Stop watching when done
function stopTracking() {
navigator.geolocation.clearWatch(watchId);
console.log('Stopped tracking');
}enableHighAccuracy: true, can significantly drain device battery. Always call clearWatch() when done.class LocationWeatherApp {
constructor() {
this.watchId = null;
}
// Get user location and fetch weather
async getWeatherForCurrentLocation() {
// Check support
if (!('geolocation' in navigator)) {
throw new Error('Geolocation not supported');
}
try {
const position = await this.getCurrentPosition();
const weather = await this.fetchWeather(
position.coords.latitude,
position.coords.longitude
);
return {
location: {
lat: position.coords.latitude,
lon: position.coords.longitude,
accuracy: position.coords.accuracy
},
weather: weather
};
} catch (error) {
this.handleLocationError(error);
throw error;
}
}
// Promisified getCurrentPosition
getCurrentPosition(options = {}) {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
resolve,
reject,
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 60000, // Cache for 1 minute
...options
}
);
});
}
// Fetch weather from API
async fetchWeather(lat, lon) {
const response = await fetch(
`https://api.weather.com/v1/geocode/${lat}/${lon}/observations.json`
);
if (!response.ok) {
throw new Error('Weather fetch failed');
}
return await response.json();
}
// Start tracking user movement
startTracking(callback) {
this.watchId = navigator.geolocation.watchPosition(
(position) => {
callback({
lat: position.coords.latitude,
lon: position.coords.longitude,
speed: position.coords.speed,
heading: position.coords.heading,
timestamp: position.timestamp
});
},
(error) => this.handleLocationError(error),
{
enableHighAccuracy: true,
maximumAge: 5000
}
);
}
// Stop tracking
stopTracking() {
if (this.watchId !== null) {
navigator.geolocation.clearWatch(this.watchId);
this.watchId = null;
}
}
// Handle errors
handleLocationError(error) {
const errorMessages = {
1: 'Permission denied. Please allow location access.',
2: 'Position unavailable. Check your GPS/WiFi.',
3: 'Request timeout. Please try again.',
};
console.error(
errorMessages[error.code] || 'Unknown location error'
);
}
// Calculate distance between two points (Haversine formula)
calculateDistance(lat1, lon1, lat2, lon2) {
const R = 6371; // Earth radius in km
const dLat = this.toRad(lat2 - lat1);
const dLon = this.toRad(lon2 - lon1);
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(this.toRad(lat1)) * Math.cos(this.toRad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c; // Distance in km
}
toRad(degrees) {
return degrees * (Math.PI / 180);
}
}
// Usage
const app = new LocationWeatherApp();
// Get weather for current location
app.getWeatherForCurrentLocation()
.then(data => {
console.log('Weather:', data.weather);
console.log('Location accuracy:', data.location.accuracy + 'm');
})
.catch(error => {
console.error('Failed:', error.message);
});
// Start tracking movement
app.startTracking((position) => {
console.log('New position:', position);
});
// Stop tracking when done
setTimeout(() => {
app.stopTracking();
}, 60000); // Stop after 1 minutePrivacy-first design with explicit consent
getCurrentPosition() and watchPosition()
Secure context required (except localhost)
High accuracy tracking drains battery