Lesson 30 of 55 · HTML
HTML5 Geolocation API
Duration: 8 min
Getting User Location
The Geolocation API lets you request the user’s latitude and longitude (with permission).
<button id='locBtn'>Show My Location</button>
<div id='coords'></div>
<script>
document.getElementById('locBtn').addEventListener('click', () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(pos => {
const { latitude, longitude } = pos.coords;
document.getElementById('coords').textContent = `Lat: ${latitude}, Lon: ${longitude}`;
}, err => {
alert('Location error: ' + err.message);
});
} else {
alert('Geolocation not supported');
}
});
</script>
Privacy & security
- Browsers require HTTPS for Geolocation.
- Users can grant or deny permission; always provide a fallback UI for those who deny or have unsupported browsers.
- Do not store raw coordinates in plain text without user consent – respect privacy regulations (GDPR, CCPA).
Practical uses
- Show nearby stores on a map.
- Provide location‑specific content (weather, local news).
- Auto‑fill address fields with a reverse‑geocoding service (server‑side).
Quick checklist for Geolocation
- Feature gated behind HTTPS? ✅
- Permission request handled gracefully (
if (navigator.geolocation)) ? ✅ - Fallback UI/message for denied permission? ✅
- No raw coordinates stored without consent? ✅
- UI updates (e.g., showing coordinates) accessible? ✅
Tip: Pair the Geolocation API with a mapping library (Leaflet, Mapbox) for a richer user experience.