Complete Guide to the JavaScript Geolocation API
Imagine visiting a website for a new coffee shop. Wouldn't it be nice if it automatically showed you the branch closest to you, rather than their headquarters in a different country? That's the power of the Geolocation API. It allows web applications to ask the user: "Where are you right now?"
In this guide, we'll cover how to access this information, how to handle users who say "No thanks," and the best practices for privacy.
Privacy First: The Permission Model
Before we write a single line of code, understand this: The user is in control.
You cannot access a user's location without their explicit permission. When you try to access the API, the browser will automatically show a prompt (like "XYZ wants to know your location").
- If they click Allow: You get the data.
- If they click Block: You get an error (and often, you can't ask again).
This means your code must always handle the "Block" scenario gracefully.
1. Getting the Current Position
The most common use case is getting a "snapshot" of where the user is right now. We use navigator.geolocation.getCurrentPosition().
Here is the basic pattern:
function getLocation() {if ("geolocation" in navigator) {// Request locationnavigator.geolocation.getCurrentPosition(success, error);} else {console.log("Geolocation is not available in this browser.");}}function success(position) {const lat = position.coords.latitude;const lng = position.coords.longitude;console.log(`You are at ${lat}, ${lng}`);}function error(err) {console.warn(`ERROR(${err.code}): ${err.message}`);}
The Coordinates Object
The position object contains more than just latitude and longitude. It can also include:
accuracy: How close the reading is (in meters).altitude: Height above sea level (if supported).speed: How fast the device is moving (great for navigation apps).
2. Handling Errors (The Right Way)
What happens if the user denies permission? Or if they are in a tunnel with no GPS?
The error callback gives us a code that tells us exactly what went wrong:
function error(err) {switch (err.code) {case err.PERMISSION_DENIED:alert("Please allow location access to use this feature.");break;case err.POSITION_UNAVAILABLE:alert("Location info is unavailable.");break;case err.TIMEOUT:alert("The request to get user location timed out.");break;default:alert("An unknown error occurred.");break;}}
Pro Tip: Never leave the user hanging. If location fails, provide a fallback—like asking them to type in their city manually.
3. Real-Time Tracking with watchPosition
Sometimes a snapshot isn't enough. If you're building a turn-by-turn navigation app or a run tracker, you need the location to update as the user moves.
For this, we use watchPosition(). It works just like setInterval—it keeps calling your success function whenever the position changes.
// Start watchingconst watchId = navigator.geolocation.watchPosition((position) => {// This runs every time the location updates!updateMapMarker(position.coords.latitude, position.coords.longitude);},error,{ enableHighAccuracy: true });// Stop watching (important to save battery!)function stopTracking() {navigator.geolocation.clearWatch(watchId);}
How Does It Know?
You might wonder how a laptop without a GPS chip knows where it is. Browsers use a mix of methods:
| Method | Accuracy | Notes |
|---|---|---|
| GPS | High (meters) | Slow, uses battery, works outdoors. |
| WiFi Triangulation | Medium | Uses nearby WiFi networks to map location. Fast and works indoors. |
| Cell Towers | Low | Uses distance from phone towers. |
| IP Address | Very Low (City level) | The fallback when nothing else works. |
UX Best Practices: Don't Be That App
We've all been there: you open a news site and immediately get slapped with "WANTS TO KNOW YOUR LOCATION." You click Block instantly. Don't prompt on page load.
Instead, wait for user interaction such as:
- User clicks "Find Stores Near Me" button.
- Then you call
getCurrentPosition. - The browser prompt appears.
The context makes the difference. If a user asks for near me content, they are much more likely to say Yes. The Geolocation API is a powerful tool for bridging the digital and physical worlds. Whether you're mapping a delivery, tagging a photo, or just finding the nearest pizza place, it all starts with those simple coordinates. Just remember: ask nicely, handle errors efficiently, and respect the user's privacy.
