Web Geolocation API

Access user's location with JavaScript for location-based features

📍 What is the Geolocation API?

The Geolocation API allows web applications to access the user's geographical location. It provides latitude and longitude coordinates, which can be used for maps, location-based services, and personalized content.


// Get user's current location
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        const lat = position.coords.latitude;
        const lon = position.coords.longitude;
        console.log(`Location: ${lat}, ${lon}`);
    });
} else {
    console.log("Geolocation not supported");
}
                                    

Output:

Location: 40.7128, -74.0060

User permission required for location access

Geolocation Features

📍

getCurrentPosition()

Get current location once

navigator.geolocation.getCurrentPosition()
🔄

watchPosition()

Track location changes

navigator.geolocation.watchPosition()
âšī¸

clearWatch()

Stop tracking location

navigator.geolocation.clearWatch(id)
đŸŽ¯

High Accuracy

GPS-level precision

enableHighAccuracy: true

🔹 Getting Current Location

Basic location retrieval with error handling:

function getLocation() {
    // Check if geolocation is supported
    if (!navigator.geolocation) {
        alert('Geolocation is not supported by this browser.');
        return;
    }
    
    // Show loading message
    document.getElementById('location-info').innerHTML = 'Getting your location...';
    
    // Get current position
    navigator.geolocation.getCurrentPosition(
        // Success callback
        function(position) {
            const coords = position.coords;
            
            const locationInfo = `
                <h3>Your Location:</h3>
                <p><strong>Latitude:</strong> ${coords.latitude}</p>
                <p><strong>Longitude:</strong> ${coords.longitude}</p>
                <p><strong>Accuracy:</strong> ${coords.accuracy} meters</p>
                <p><strong>Timestamp:</strong> ${new Date(position.timestamp).toLocaleString()}</p>
            `;
            
            document.getElementById('location-info').innerHTML = locationInfo;
            
            // Optional: Show on map
            showOnMap(coords.latitude, coords.longitude);
        },
        
        // Error callback
        function(error) {
            let errorMessage = '';
            
            switch(error.code) {
                case error.PERMISSION_DENIED:
                    errorMessage = 'Location access denied by user.';
                    break;
                case error.POSITION_UNAVAILABLE:
                    errorMessage = 'Location information unavailable.';
                    break;
                case error.TIMEOUT:
                    errorMessage = 'Location request timed out.';
                    break;
                default:
                    errorMessage = 'An unknown error occurred.';
                    break;
            }
            
            document.getElementById('location-info').innerHTML = 
                `<p style="color: red;">Error: ${errorMessage}</p>`;
        }
    );
}

function showOnMap(lat, lon) {
    // Create Google Maps link
    const mapUrl = `https://www.google.com/maps?q=${lat},${lon}`;
    document.getElementById('map-link').innerHTML = 
        `<a href="${mapUrl}" target="_blank">View on Google Maps</a>`;
}

Location Demo:

Your Location:

Latitude: 40.7128

Longitude: -74.0060

Accuracy: 50 meters

View on Google Maps

🔹 Location Options

Configure location requests with options:

// Location options
const locationOptions = {
    enableHighAccuracy: true,    // Use GPS if available
    timeout: 10000,             // 10 seconds timeout
    maximumAge: 60000           // Accept cached location up to 1 minute old
};

function getHighAccuracyLocation() {
    navigator.geolocation.getCurrentPosition(
        function(position) {
            const coords = position.coords;
            
            console.log('High accuracy location:');
            console.log('Latitude:', coords.latitude);
            console.log('Longitude:', coords.longitude);
            console.log('Accuracy:', coords.accuracy, 'meters');
            
            // Additional properties (may not always be available)
            if (coords.altitude !== null) {
                console.log('Altitude:', coords.altitude, 'meters');
            }
            
            if (coords.speed !== null) {
                console.log('Speed:', coords.speed, 'm/s');
            }
            
            if (coords.heading !== null) {
                console.log('Heading:', coords.heading, 'degrees');
            }
            
            displayLocationDetails(coords);
        },
        
        function(error) {
            console.error('Location error:', error.message);
            handleLocationError(error);
        },
        
        locationOptions  // Pass options here
    );
}

function displayLocationDetails(coords) {
    const details = document.getElementById('location-details');
    details.innerHTML = `
        <div class="location-card">
            <h3>📍 Location Details</h3>
            <p>Coordinates: ${coords.latitude.toFixed(6)}, ${coords.longitude.toFixed(6)}</p>
            <p>Accuracy: Âą${coords.accuracy}m</p>
            ${coords.altitude ? `<p>Altitude: ${coords.altitude}m</p>` : ''}
            ${coords.speed ? `<p>Speed: ${(coords.speed * 3.6).toFixed(1)} km/h</p>` : ''}
        </div>
    `;
}

Location Options:

Option Description
enableHighAccuracy Use GPS for better accuracy
timeout Maximum time to wait (ms)
maximumAge Accept cached location age (ms)

🔹 Watching Position Changes

Track location changes in real-time:

let watchId = null;
let locationHistory = [];

function startWatchingLocation() {
    if (!navigator.geolocation) {
        alert('Geolocation not supported');
        return;
    }
    
    const options = {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 0  // Always get fresh location
    };
    
    // Start watching position
    watchId = navigator.geolocation.watchPosition(
        function(position) {
            const coords = position.coords;
            const timestamp = new Date(position.timestamp);
            
            // Add to history
            locationHistory.push({
                lat: coords.latitude,
                lon: coords.longitude,
                accuracy: coords.accuracy,
                time: timestamp
            });
            
            // Update display
            updateLocationDisplay(coords, timestamp);
            
            // Keep only last 10 locations
            if (locationHistory.length > 10) {
                locationHistory.shift();
            }
            
            console.log('Location updated:', coords.latitude, coords.longitude);
        },
        
        function(error) {
            console.error('Watch position error:', error.message);
            document.getElementById('watch-status').innerHTML = 
                `<p style="color: red;">Error: ${error.message}</p>`;
        },
        
        options
    );
    
    document.getElementById('watch-status').innerHTML = 
        '<p style="color: green;">📍 Watching your location...</p>';
    
    // Enable stop button
    document.getElementById('stop-watch-btn').disabled = false;
}

function stopWatchingLocation() {
    if (watchId !== null) {
        navigator.geolocation.clearWatch(watchId);
        watchId = null;
        
        document.getElementById('watch-status').innerHTML = 
            '<p>Location watching stopped.</p>';
        
        // Disable stop button
        document.getElementById('stop-watch-btn').disabled = true;
    }
}

function updateLocationDisplay(coords, timestamp) {
    const display = document.getElementById('current-location');
    display.innerHTML = `
        <div class="location-update">
            <h4>Current Location</h4>
            <p>📍 ${coords.latitude.toFixed(6)}, ${coords.longitude.toFixed(6)}</p>
            <p>đŸŽ¯ Accuracy: Âą${coords.accuracy}m</p>
            <p>🕒 Updated: ${timestamp.toLocaleTimeString()}</p>
            <p>📊 Total updates: ${locationHistory.length}</p>
        </div>
    `;
}

Location Tracking Demo:

Current Location

📍 40.712800, -74.006000

đŸŽ¯ Accuracy: Âą25m

🕒 Updated: 2:30:45 PM

📊 Total updates: 3

🔹 Distance Calculation

Calculate distance between two locations:

// Calculate distance between two points using Haversine formula
function calculateDistance(lat1, lon1, lat2, lon2) {
    const R = 6371; // Earth's radius in kilometers
    
    const dLat = toRadians(lat2 - lat1);
    const dLon = toRadians(lon2 - lon1);
    
    const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
              Math.cos(toRadians(lat1)) * Math.cos(toRadians(lat2)) *
              Math.sin(dLon/2) * Math.sin(dLon/2);
    
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    const distance = R * c;
    
    return distance; // Distance in kilometers
}

function toRadians(degrees) {
    return degrees * (Math.PI / 180);
}

// Example: Find distance to a landmark
function findDistanceToLandmark() {
    // Example coordinates (Statue of Liberty)
    const landmarkLat = 40.6892;
    const landmarkLon = -74.0445;
    
    navigator.geolocation.getCurrentPosition(function(position) {
        const userLat = position.coords.latitude;
        const userLon = position.coords.longitude;
        
        const distance = calculateDistance(userLat, userLon, landmarkLat, landmarkLon);
        
        document.getElementById('distance-info').innerHTML = `
            <div class="distance-card">
                <h3>đŸ—Ŋ Distance to Statue of Liberty</h3>
                <p><strong>Distance:</strong> ${distance.toFixed(2)} km</p>
                <p><strong>Distance:</strong> ${(distance * 0.621371).toFixed(2)} miles</p>
                <p><strong>Your location:</strong> ${userLat.toFixed(4)}, ${userLon.toFixed(4)}</p>
                <p><strong>Landmark:</strong> ${landmarkLat}, ${landmarkLon}</p>
            </div>
        `;
    });
}

// Track movement distance
let lastPosition = null;
let totalDistance = 0;

function trackMovement() {
    navigator.geolocation.watchPosition(function(position) {
        const currentLat = position.coords.latitude;
        const currentLon = position.coords.longitude;
        
        if (lastPosition) {
            const distance = calculateDistance(
                lastPosition.lat, lastPosition.lon,
                currentLat, currentLon
            );
            
            totalDistance += distance;
            
            document.getElementById('movement-tracker').innerHTML = `
                <p>đŸšļ Total distance moved: ${(totalDistance * 1000).toFixed(1)} meters</p>
                <p>📍 Current: ${currentLat.toFixed(6)}, ${currentLon.toFixed(6)}</p>
            `;
        }
        
        lastPosition = { lat: currentLat, lon: currentLon };
    });
}

Distance Calculation:

đŸ—Ŋ Distance to Statue of Liberty

Distance: 2.34 km

Distance: 1.45 miles

Your location: 40.7128, -74.0060

Landmark: 40.6892, -74.0445

🔹 Privacy and Best Practices

🔒 Privacy Considerations:

  • User Permission: Always required for location access
  • HTTPS Required: Geolocation only works on secure connections
  • Clear Purpose: Explain why you need location data
  • Data Storage: Be transparent about how location is stored

✅ Best Practices:

  • Graceful Degradation: App should work without location
  • Error Handling: Handle all possible error scenarios
  • Battery Consideration: High accuracy uses more battery
  • Clear Watch: Always stop watching when not needed
// Example of good location request with user explanation
function requestLocationWithExplanation() {
    // Show explanation first
    const userConsent = confirm(
        'This app would like to access your location to show nearby restaurants. ' +
        'Your location data will not be stored or shared. Allow location access?'
    );
    
    if (!userConsent) {
        // Provide alternative functionality
        showManualLocationInput();
        return;
    }
    
    // Request location with appropriate options
    const options = {
        enableHighAccuracy: false,  // Save battery for this use case
        timeout: 10000,
        maximumAge: 300000  // 5 minutes cache is OK for restaurants
    };
    
    navigator.geolocation.getCurrentPosition(
        handleLocationSuccess,
        handleLocationError,
        options
    );
}

🧠 Test Your Knowledge

Which method gets the user's location once?