Lesson 30 of 55
HTMLHTML5 Geolocation API
8 min
Course progress55%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 30 of 55
HTML8 min
Keep these ideas in mind as you work through the lesson.
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>
if (navigator.geolocation)) ? ✅Tip: Pair the Geolocation API with a mapping library (Leaflet, Mapbox) for a richer user experience.