HTML Geolocation API Tutorial: How to Get User Location with JavaScript (Step-by-Step Guide)
HTML Tutorials · HTML Geolocation API Tag · Introduction
HTML Geolocation API Explained: How to Get User Location Using JavaScript (Beginner to Advanced Guide)
🔸HTML Geolocation API allows a website to access the geographical location of the user's device (with their permissions). This is commonly used in maps, delivery apps, or local services. Here's a basic example.
What Exactly Is the Geolocation API?
🔸 The Geolocation API isn't an HTML tag at all — it's a JavaScript interface, exposed on the browser's global navigator object as navigator.geolocation, that asks the operating system for the device's current physical position. Under the hood, the browser combines whatever location signals the device has available — GPS on a phone, nearby Wi-Fi network fingerprinting, cell-tower triangulation, or a rough IP-address lookup on a desktop — and returns whichever result it can produce with the highest confidence.
🔒 Important -
✅ Works only on secure origins (https:// or localhost)
✅ Asks the user for permission to access location
✅ Returns latitude and longitude
✅ Can be extended with Google Maps, Leaflet, or other mapping libraries
✅ Basic Geolocation API HTML code Example:-
My Location
Click the button to get your location.
<!DOCTYPE html>
<html>
<head>
<title>Geolocation API Example</title>
</head>
<body>
<h1>My Location</h1>
<p id="location">Click the button to get your location.</p>
<button onclick="getLocation()">Get Location</button>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
document.getElementById("location").innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
document.getElementById("location").innerHTML =
"Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
function showError(error) {
let msg;
switch(error.code) {
case error.PERMISSION_DENIED:
msg = "User denied the request for Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
msg = "Location information is unavailable.";
break;
case error.TIMEOUT:
msg = "The request to get user location timed out.";
break;
case error.UNKNOWN_ERROR:
msg = "An unknown error occurred.";
break;
}
document.getElementById("location").innerHTML = msg;
}
</script>
</body>
</html>
🔸 Clicking the button above triggers a genuine browser permission prompt (or uses a previously saved choice) and, if allowed, reports your actual approximate coordinates back in this page — exactly the same three-function pattern shown in the code: a trigger function, a success callback that receives a position object, and an error callback that inspects error.code to report what went wrong.
Breaking Down the position.coords Object
🔸 The showPosition callback above reads position.coords.latitude and position.coords.longitude, but the full coords object carries several more properties worth knowing about.
| Property | Meaning |
|---|---|
| latitude / longitude | The device's coordinates in decimal degrees |
| accuracy | The radius of certainty around the reported position, in meters |
| altitude | Height above sea level, in meters (often null if unavailable) |
| altitudeAccuracy | Certainty radius for the altitude reading, in meters |
| heading | Direction of travel in degrees, only meaningful while moving |
| speed | Current speed in meters per second, if the device can determine it |
Understanding the Four Error Codes
🔸 The showError function's switch statement handles every possible failure the API can report, and knowing what triggers each one helps you write clearer user-facing messages than the generic examples above.
| Error Code | What It Means |
|---|---|
| PERMISSION_DENIED | The user explicitly clicked "Block" on the location permission prompt |
| POSITION_UNAVAILABLE | The device's location sensors couldn't determine a position at all |
| TIMEOUT | The request took longer than the allowed time (see timeout option below) and was abandoned |
| UNKNOWN_ERROR | A generic failure that doesn't fit the three categories above |
Optional Configuration: The PositionOptions Object
🔸 getCurrentPosition accepts an optional third argument beyond the success and error callbacks shown in the basic example, letting you fine-tune accuracy and timing behavior.
navigator.geolocation.getCurrentPosition(showPosition, showError, {
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
});
| Option | Effect |
|---|---|
| enableHighAccuracy | Requests the most precise reading available (typically GPS), at the cost of extra battery use and time |
| timeout | Maximum milliseconds to wait before firing the TIMEOUT error |
| maximumAge | Allows the browser to reuse a cached position up to this many milliseconds old, instead of requesting a fresh one |
getCurrentPosition vs watchPosition
🔸 The basic example above uses getCurrentPosition, which fetches the location exactly once. A second method, watchPosition, is built for continuous tracking.
| Method | Behavior | Best For |
|---|---|---|
| getCurrentPosition() | Fires the callback once with the current location | "Find my location" buttons, one-time address lookup |
| watchPosition() | Fires the callback repeatedly whenever position changes | Live navigation, delivery tracking, fitness apps |
const watchId = navigator.geolocation.watchPosition(showPosition, showError);
// Later, to stop tracking:
navigator.geolocation.clearWatch(watchId);
Real-World Use Cases
| Use Case | How Geolocation Helps |
|---|---|
| Store locator / "find nearest branch" | Calculates distance from the visitor's coordinates to each location |
| Food delivery apps | Auto-fills the delivery address or tracks a driver's live position with watchPosition |
| Weather websites | Shows local forecast automatically without the visitor typing their city |
| Maps and directions | Centers the map on the user's current position as the starting point |
| Local business search | Filters and ranks results by proximity to the visitor |
Why HTTPS Is Required
🔸 As the "Important" section above notes, the Geolocation API only works on secure origins — a page served over https://, or a page loaded from localhost during development. This restriction exists because location data is highly sensitive, and browsers refuse to expose it over an unencrypted http:// connection where the request and response could be intercepted or tampered with in transit.
Privacy and Permission Best Practices
- 🔸 Only request location when the feature genuinely needs it; asking immediately on page load with no context feels invasive and increases the chance of a "Block" response.
- 🔸 Explain why you need the location before triggering the browser's permission prompt, such as a short line of text next to the "Get Location" button.
- 🔸 Always implement showError gracefully; a visitor who denies permission should still be able to use the rest of the page, ideally by typing an address manually as a fallback.
- 🔸 Never store or transmit a user's coordinates without clearly disclosing that in your privacy policy.
Common Mistakes with the Geolocation API
- 🔸 Forgetting the if (navigator.geolocation) check: a small number of older or restricted browsers don't support the API at all, and this guard prevents a hard JavaScript error.
- 🔸 Testing on plain HTTP: the API silently fails or the browser blocks it outright outside of HTTPS and localhost.
- 🔸 Assuming perfect accuracy: desktop and Wi-Fi-based positioning can be off by a city block or more; always check position.coords.accuracy before treating a reading as precise.
- 🔸 Leaving watchPosition running unnecessarily: forgetting to call clearWatch() when tracking is no longer needed drains battery on mobile devices.
- 🔸 Not handling denied permission gracefully: a page that breaks entirely when location access is refused creates a poor experience for privacy-conscious visitors.
Geolocation API Best Practices
- 🔸 Always feature-detect with if (navigator.geolocation) before calling any geolocation method.
- 🔸 Serve your site over HTTPS in production; the API simply won't work otherwise.
- 🔸 Set a sensible timeout so users aren't left waiting indefinitely on a slow or failed lookup.
- 🔸 Use watchPosition only for genuine live-tracking features, and always pair it with clearWatch when done.
- 🔸 Combine the returned coordinates with a mapping library like Leaflet or Google Maps to actually display the location visually, rather than showing raw numbers.
- 🔸 Provide a manual fallback (such as a text input for an address or postal code) for visitors who decline the permission prompt.
Try It Yourself (Copy This Code and Paste. See how it works). Paste the example above into the live playground below.
Live Code Preview
Practice Exercises: Test the Geolocation API
- Rebuild the basic example, then add position.coords.accuracy to the displayed output.
- Add enableHighAccuracy: true and a 10-second timeout to your getCurrentPosition call.
- Convert your example from getCurrentPosition to watchPosition and log each update to the console.
- Add a clearWatch call triggered by a "Stop Tracking" button.
- Write a friendlier error message for each of the four error codes than the ones shown in this tutorial.
Frequently Asked Questions About the HTML Geolocation API
What is the Geolocation API?
It is a browser API that allows websites to access the user's location.
Is Geolocation API safe?
Yes, it requires user permission before accessing location.
Do I need HTTPS for Geolocation?
Yes, modern browsers require HTTPS for geolocation access.
How accurate is the Geolocation API?
Accuracy varies by device and available sensors: GPS-equipped mobile devices can be accurate to a few meters, while desktops relying on Wi-Fi or IP-based lookup may only be accurate to within a city or neighborhood.
What is the difference between getCurrentPosition and watchPosition?
getCurrentPosition retrieves the device's location a single time, while watchPosition continuously monitors position and calls its callback every time the location changes, which is useful for live tracking such as turn-by-turn navigation.
Conclusion
🔸 The Geolocation API distills down to three moving parts: feature-detect with navigator.geolocation, call getCurrentPosition (or watchPosition for continuous tracking) with a success and an error callback, and read the resulting coordinates off position.coords. Layer on HTTPS, thoughtful permission timing, and a graceful fallback for denied requests, and you have everything needed to power store locators, delivery tracking, local search, and map-centered experiences. Work through the example above, then try wiring your own result into a mapping library like Leaflet or Google Maps.