JavaScript
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Types
-
Section 3: Strings and Numbers in Depth
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Objects and Arrays
-
Section 7: Maps, Sets, and Symbols
-
Section 8: Asynchronous JavaScript
-
Section 9: Object-Oriented and Prototypes
-
Section 10: The DOM
-
Section 11: Browser APIs
-
Section 12: Modern JavaScript (ES2015-ES2025)
-
Section 13: Functional Programming Patterns
-
Section 14: Error Handling and Debugging
-
Section 15: Testing
-
Section 16: Accessibility for JavaScript Developers
-
Section 17: Internationalization and Localization
-
Section 18: Performance
-
Section 19: Node.js Fundamentals
-
Section 20: Regular Expressions
-
Section 21: Design Patterns in JavaScript
-
Section 22: Security Basics
-
Section 23: Data Structures and Algorithms in JavaScript
-
Section 24: Practical Projects
-
Section 25: More Advanced Async Patterns
-
Section 26: More Object and Class Practice
-
Section 27: Working with Dates and Internationalization
-
Section 28: Web Components
-
Section 29: More DOM and Browser Practice
-
Section 30: Build Tooling for Vanilla JavaScript
-
Section 31: More Practice Projects
-
Section 32: Interview and Algorithm Practice
-
Section 33: Error Objects (MDN Reference)
-
Section 34: TypedArrays and Binary Data
-
Section 35: Reflection and Metaprogramming (MDN Reference)
-
Section 36: More Global Functions (MDN Reference)
91: Geolocation API
Imagine you're at a massive outdoor music festival. You've wandered too far from your friends and you have no idea where the food trucks are. You pull out your phone and ask, "Where am I right now?" Your phone doesn't just magically know; it sends out a request to GPS satellites and nearby cell towers, waits for them to respond, and then translates those signals into a coordinate on a map. It's a conversation: you ask for the location, the system verifies you have permission to know, and then it hands you the coordinates.
The Geolocation API works exactly like that. In JavaScript, the navigator.geolocation object is your interface to the device's location hardware. Here is how that festival analogy maps to the code:
- Asking "Where am I?" is calling
getCurrentPosition(). - The permission popup is the browser's security layer ensuring the user actually wants to share their location with your site.
- The coordinates are delivered as a
Positionobject containing the latitude and longitude. - The "lost signal" is handled by an error callback if the GPS is off or the user says "No."
Asking the Browser for a Pin on the Map
To get a user's location, we use navigator.geolocation.getCurrentPosition(). Now, this is an asynchronous operation. The browser can't just freeze your whole website while it waits for a satellite in space to respond, so it uses callbacks. You provide one function to handle success and another to handle failure.
const findMe = () => {
navigator.geolocation.getCurrentPosition(
(position) => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
console.log(`You are at Lat: ${lat}, Lon: ${lon}`);
},
(error) => {
console.error(`Error getting location: ${error.message}`);
}
);
};
findMe();
I should mention that this will only work over HTTPS. Browsers consider location data extremely sensitive, so if you're trying to run this on a plain HTTP site in production, it'll just fail silently or throw a security error. Localhost is usually an exception for development purposes.
Dealing with "No" and "I can't find you"
In a real app, you can't just assume the user will click "Allow." People are protective of their privacy, and sometimes the hardware simply fails. The error callback provides a GeolocationPositionError object. I always recommend checking the code property of that error to give the user a helpful message instead of a generic "something went wrong."
navigator.geolocation.getCurrentPosition(
(pos) => { /* handle success */ },
(err) => {
switch(err.code) {
case err.PERMISSION_DENIED:
alert("You denied the request for Geolocation. I can't find your nearby coffee shops!");
break;
case err.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case err.TIMEOUT:
alert("The request to get user location timed out.");
break;
default:
alert("An unknown error occurred.");
break;
}
}
);
Keeping Tabs on a Moving Target
Sometimes getCurrentPosition isn't enough. If you're building a fitness tracker or a delivery app, you need to know when the user moves. That's where watchPosition() comes in. It works almost identically to the previous method, but instead of firing once, it keeps the "conversation" open and triggers the success callback every time the device's location changes significantly.
const watchId = navigator.geolocation.watchPosition(
(position) => {
console.log(`Moved to: ${position.coords.latitude}, ${position.coords.longitude}`);
},
(error) => { console.error(error); },
{
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
}
);
// When you're done tracking, don't forget to stop it to save battery!
// navigator.geolocation.clearWatch(watchId);
Notice the third argument in watchPosition? Those are options. enableHighAccuracy: true tells the device to use GPS rather than just Wi-Fi triangulation. It's more precise, but it'll drain the user's battery faster—use it sparingly.
📋 Practical Task
Build a "Local Weather Trigger" Simulator
Create a small application that simulates a weather alert system based on a user's actual location. Your code should:
- Implement a button labeled "Check Local Weather".
- When clicked, use the Geolocation API to retrieve the user's current latitude and longitude.
- If the location is successfully retrieved, display a message saying: "Fetching weather for coordinates: [Lat], [Lon]..."
- If the user denies permission, display a specific message: "Weather access denied. Please enable location permissions in your browser settings to see local forecasts."
- Include a "Stop Tracking" button that uses
clearWatch()to stop a backgroundwatchPosition()process that logs the coordinates to the console every time the user moves.
There are no comments for now.