HTML5 APIs
Geolocation API
Access user location with the HTML5 Geolocation API. Build location-aware applications like store finders, weather apps, and local search features.
What is the Geolocation API?
The Geolocation API allows websites to request the user's geographic location. It provides latitude, longitude, altitude, speed, and accuracy information.
📠Coordinates
Get latitude and longitude
🎯 Accuracy
Know precision of location data
🔒 Privacy-First
Requires user permission
📱 Mobile & Desktop
Works on all modern devices
Basic Geolocation Request
HTML
<!DOCTYPE html>
<html>
<head>
<title>Geolocation Demo</title>
</head>
<body>
<button onclick="getLocation()">Get My Location</button>
<div id="result"></div>
<script>
function getLocation() {
if (navigator.geolocation) {
// Browser supports geolocation
navigator.geolocation.getCurrentPosition(
showPosition, // Success callback
showError // Error callback
);
} else {
document.getElementById('result').textContent =
'Geolocation is not supported by this browser.';
}
}
function showPosition(position) {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
const accuracy = position.coords.accuracy;
document.getElementById('result').innerHTML = `
<p><strong>Latitude:</strong> ${lat}</p>
<p><strong>Longitude:</strong> ${lon}</p>
<p><strong>Accuracy:</strong> ${accuracy} meters</p>
`;
}
function showError(error) {
const messages = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
document.getElementById('result').textContent =
'Error: ' + messages[error.code];
}
</script>
</body>
</html>Position Object Properties
Coordinates (position.coords)
| Property | Description | Always Available |
|---|---|---|
latitude | Latitude in decimal degrees | ✅ Yes |
longitude | Longitude in decimal degrees | ✅ Yes |
accuracy | Accuracy in meters | ✅ Yes |
altitude | Altitude in meters (above sea level) | ⌠Optional |
altitudeAccuracy | Altitude accuracy in meters | ⌠Optional |
heading | Direction of travel (degrees from north) | ⌠Optional |
speed | Speed in meters per second | ⌠Optional |
JAVASCRIPT
function showPosition(position) {
const coords = position.coords;
console.log('Latitude:', coords.latitude);
console.log('Longitude:', coords.longitude);
console.log('Accuracy:', coords.accuracy, 'meters');
// Optional properties (may be null)
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');
}
// Timestamp
console.log('Time:', new Date(position.timestamp));
}Geolocation Options
JAVASCRIPT
const options = {
enableHighAccuracy: true, // Request best accuracy
timeout: 10000, // Max wait time (ms)
maximumAge: 0 // Don't use cached position
};
navigator.geolocation.getCurrentPosition(
showPosition,
showError,
options
);Options Explained
- enableHighAccuracy:
trueuses GPS (more accurate but slower, more battery),falseuses WiFi/IP (faster but less accurate) - timeout: Maximum time (milliseconds) to wait for position. Default is Infinity.
- maximumAge: Maximum age (milliseconds) of cached position. 0 means always get fresh position. Default is 0.
Watching Position (Live Updates)
JAVASCRIPT
let watchId;
// Start watching position
function startTracking() {
watchId = navigator.geolocation.watchPosition(
updatePosition,
showError,
{ enableHighAccuracy: true }
);
}
// Stop watching
function stopTracking() {
if (watchId) {
navigator.geolocation.clearWatch(watchId);
console.log('Stopped tracking');
}
}
// Called every time position changes
function updatePosition(position) {
const { latitude, longitude, speed } = position.coords;
console.log('Position update:');
console.log(' Lat:', latitude);
console.log(' Lon:', longitude);
console.log(' Speed:', speed ? `${speed} m/s` : 'Unknown');
// Update map, etc.
updateMap(latitude, longitude);
}
// Usage
document.getElementById('start-btn').onclick = startTracking;
document.getElementById('stop-btn').onclick = stopTracking;Error Handling
JAVASCRIPT
function handleError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
console.error('User denied geolocation request');
showMessage('Please enable location access in browser settings');
break;
case error.POSITION_UNAVAILABLE:
console.error('Location information unavailable');
showMessage('Unable to determine your location');
break;
case error.TIMEOUT:
console.error('Location request timed out');
showMessage('Location request took too long');
break;
default:
console.error('Unknown error:', error.message);
showMessage('An error occurred while getting location');
}
}
// Error codes
// error.PERMISSION_DENIED = 1
// error.POSITION_UNAVAILABLE = 2
// error.TIMEOUT = 3Practical Example: Store Finder
HTML
<!DOCTYPE html>
<html>
<head>
<title>Store Finder</title>
<style>
.store { margin: 10px 0; padding: 10px; border: 1px solid #ddd; }
.distance { color: #666; font-size: 0.9em; }
</style>
</head>
<body>
<h1>Find Nearest Store</h1>
<button onclick="findNearestStores()">Find Stores Near Me</button>
<div id="stores"></div>
<script>
const stores = [
{ name: 'Store A', lat: 40.7128, lon: -74.0060 },
{ name: 'Store B', lat: 34.0522, lon: -118.2437 },
{ name: 'Store C', lat: 41.8781, lon: -87.6298 }
];
function findNearestStores() {
navigator.geolocation.getCurrentPosition(position => {
const userLat = position.coords.latitude;
const userLon = position.coords.longitude;
// Calculate distances
const storesWithDistance = stores.map(store => ({
...store,
distance: calculateDistance(
userLat, userLon,
store.lat, store.lon
)
}));
// Sort by distance
storesWithDistance.sort((a, b) => a.distance - b.distance);
// Display
const html = storesWithDistance.map(store => `
<div class="store">
<strong>${store.name}</strong>
<div class="distance">${store.distance.toFixed(1)} km away</div>
</div>
`).join('');
document.getElementById('stores').innerHTML = html;
}, error => {
alert('Unable to get location: ' + error.message);
});
}
// Haversine formula for distance calculation
function calculateDistance(lat1, lon1, lat2, lon2) {
const R = 6371; // Earth 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;
}
</script>
</body>
</html>Integration with Google Maps
HTML
<!DOCTYPE html>
<html>
<head>
<title>Location on Map</title>
<style>
#map { height: 400px; width: 100%; }
</style>
</head>
<body>
<button onclick="showLocationOnMap()">Show My Location</button>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
<script>
let map;
function showLocationOnMap() {
navigator.geolocation.getCurrentPosition(position => {
const { latitude, longitude } = position.coords;
// Create map centered on user location
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: latitude, lng: longitude },
zoom: 15
});
// Add marker at user location
new google.maps.Marker({
position: { lat: latitude, lng: longitude },
map: map,
title: 'You are here',
icon: {
url: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
}
});
// Add info window
const infoWindow = new google.maps.InfoWindow({
content: `
<strong>Your Location</strong><br>
Lat: ${latitude.toFixed(4)}<br>
Lon: ${longitude.toFixed(4)}<br>
Accuracy: ${position.coords.accuracy.toFixed(0)}m
`
});
infoWindow.open(map, marker);
}, error => {
alert('Error: ' + error.message);
});
}
</script>
</body>
</html>Security & Privacy
HTTPS Required
âš ï¸ Geolocation API only works on HTTPS sites (except localhost).
User Permission
- ✅ Browser prompts user for permission
- ✅ User can deny or allow
- ✅ Permission is remembered for site
- ✅ User can revoke permission anytime
Best Practices
- 🔒 Explain why you need location before requesting
- 🔒 Only request when needed (not on page load)
- 🔒 Provide fallback if user denies permission
- 🔒 Don't store location longer than necessary
- 🔒 Be transparent about how location is used
Browser Support
Geolocation API is supported in all modern browsers:
- ✅ Chrome 5+
- ✅ Firefox 3.5+
- ✅ Safari 5+
- ✅ Edge (all versions)
- ✅ iOS Safari 3.2+
- ✅ Android Browser 2.1+
Feature Detection
JAVASCRIPT
if ('geolocation' in navigator) {
// Geolocation is supported
navigator.geolocation.getCurrentPosition(/* ... */);
} else {
// Fallback: ask user to enter location manually
showManualLocationInput();
}Complete Working Example
HTML
<!DOCTYPE html>
<html>
<head>
<title>Geolocation Demo</title>
<style>
body { font-family: Arial, sans-serif; max-width: 600px; margin: 50px auto; }
button { padding: 10px 20px; font-size: 16px; cursor: pointer; }
#result { margin-top: 20px; padding: 20px; background: #f5f5f5; border-radius: 8px; }
.loading { color: #666; }
.error { color: #d32f2f; }
.success { color: #388e3c; }
</style>
</head>
<body>
<h1>HTML5 Geolocation Demo</h1>
<button onclick="getLocation()">Get My Location</button>
<div id="result"></div>
<script>
function getLocation() {
const result = document.getElementById('result');
if (!navigator.geolocation) {
result.innerHTML = '<p class="error">Geolocation not supported</p>';
return;
}
result.innerHTML = '<p class="loading">Getting location...</p>';
const options = {
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
};
navigator.geolocation.getCurrentPosition(
position => {
const { latitude, longitude, accuracy } = position.coords;
result.innerHTML = `
<p class="success"><strong>Location found!</strong></p>
<p><strong>Latitude:</strong> ${latitude.toFixed(6)}</p>
<p><strong>Longitude:</strong> ${longitude.toFixed(6)}</p>
<p><strong>Accuracy:</strong> ±${accuracy.toFixed(0)} meters</p>
<p><a href="https://www.google.com/maps?q=${latitude},${longitude}"
target="_blank">View on Google Maps</a></p>
`;
},
error => {
const errors = {
1: 'Permission denied. Please enable location access.',
2: 'Position unavailable. Please check your device settings.',
3: 'Request timeout. Please try again.'
};
result.innerHTML = `<p class="error">${errors[error.code]}</p>`;
},
options
);
}
</script>
</body>
</html>