Geolocation API
Location services, maps integration, and location-based features.
Overview
Geolocation provides user location data for location-based features.
Key Concepts
- getCurrentPosition — Get current location
- watchPosition — Track location changes
- Permission — User must grant access
- Accuracy — GPS, WiFi, cell tower based
- Privacy — Respect user privacy
Code Examples
<button id="getLocation">Get My Location</button>
<div id="map" style="width: 100%; height: 400px;"></div>
<script>
const mapDiv = document.getElementById('map');
let watchId;
document.getElementById('getLocation').addEventListener('click', () => {
if (!navigator.geolocation) {
alert('Geolocation not supported');
return;
}
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude, accuracy } = position.coords;
mapDiv.innerHTML = `
<p>Latitude: ${latitude}</p>
<p>Longitude: ${longitude}</p>
<p>Accuracy: ${accuracy}m</p>
`;
},
(error) => {
switch(error.code) {
case error.PERMISSION_DENIED:
alert('Location access denied');
break;
case error.POSITION_UNAVAILABLE:
alert('Location unavailable');
break;
case error.TIMEOUT:
alert('Location request timed out');
break;
}
},
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
}
);
});
// Watch position
function startTracking() {
watchId = navigator.geolocation.watchPosition(
(position) => {
console.log('Location updated:', position.coords);
},
(error) => console.error(error)
);
}
function stopTracking() {
navigator.geolocation.clearWatch(watchId);
}
</script>
Practice
Build a location-based weather app using the Geolocation API.