HTML5
Geolocation
Get the user's position and watch for changes.
By EZ4Code Team
geolocationlocation
Code
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(
pos => {
const { latitude, longitude, accuracy } = pos.coords;
console.log("Lat:", latitude, "Lng:", longitude, "+/-", accuracy, "m");
},
err => {
console.error(err.message); // permission denied, etc.
},
{ enableHighAccuracy: true, timeout: 10000, maximumAge: 0 }
);
} else {
console.log("Geolocation not supported");
}
// Watch position changes (e.g., for navigation)
const watchId = navigator.geolocation.watchPosition(
pos => console.log(pos.coords),
err => console.error(err)
);
// Stop watching
navigator.geolocation.clearWatch(watchId);Explanation
navigator.geolocation prompts the user for permission and returns coordinates via a callback. getCurrentPosition takes success and error callbacks plus options like enableHighAccuracy for GPS. watchPosition streams updates and returns an id used with clearWatch to stop tracking.
More HTML5 Snippets
Semantic Elements
Structure a page with header, nav, main, article, and footer.
Form Input Types
Use native HTML5 input types, validation, and datalist.
Canvas Basics
Draw shapes, lines, and text on a 2D canvas.
Video & Audio
Embed media with multiple sources and control playback.
Local & Session Storage
Persist data in the browser with the Web Storage API.
Drag and Drop
Accept dropped files with the Drag and Drop API.