Concept Explanation
The Geolocation API allows your app to ask the user: "Where are you?" It relies on GPS, Wi-Fi, or IP addresses to find the user's longitude and latitude. Crucially, it is a privacy-first API — the browser will always show a popup asking for permission first.
Syntax or Core Structure
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude } = position.coords;
console.log(`You are at ${latitude}, ${longitude}`);
},
(error) => {
console.log("User denied access or GPS failed.");
}
);
Real World Example
A Weather App: As soon as you open it, the app asks for your location. It finds you are in "Mumbai" and automatically fetches the rain forecast for your specific street.
Best Practices
- High Accuracy: You can pass an
optionsobject to requestenableHighAccuracy: true, which uses GPS instead of just Wi-Fi. - Handle Denial: Always write a "Fallback" plan for what happens if the user clicks "Block." Show them a manual search bar instead.
- Secure Over HTTPS: In modern browsers, Geolocation only works on secure (HTTPS) websites for security reasons.
Practice Exercises
- The Finder: Write a script that prints a Google Maps link to your current location in the console.
- The Tracker: Research
watchPosition()and explain how it differs fromgetCurrentPosition(). - The Permission Guard: Use the
Permissions APIto check if the user has already granted location access before you ask for it.