JavaScript - Geolocation API
Overview
Estimated time: 15–20 minutes
The Geolocation API allows web apps to access the user's location (with permission).
Learning Objectives
- Request and use the user's location in JavaScript.
- Handle permissions and errors.
Prerequisites
Getting the User's Location
navigator.geolocation.getCurrentPosition(
function(position) {
console.log(position.coords.latitude, position.coords.longitude);
},
function(error) {
console.error(error);
}
);
Common Pitfalls
- Requires user permission; may fail if denied or unsupported.
Summary
The Geolocation API is useful for location-based features, but always handle errors and permissions gracefully.