The HTML Geolocation API enables web applications to obtain the user's geographic coordinates (latitude and longitude) with their explicit permission, powering location-aware services like maps, weather forecasts, and local store locators.
Accessing location coordinates is managed via navigator.geolocation in JavaScript:
// Request current position coordinates
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
}
Core Geolocation API methods:
getCurrentPosition(): Obtains the user's current geographic position once.watchPosition(): Listens continuously to position changes as the user moves (ideal for navigation apps).clearWatch(): Stops an active watchPosition() tracking process.flowchart TD
A["Web App Calls navigator.geolocation"] --> B["Browser Displays Permission Prompt"]
B -- User Denies --> C["Error Callback (Permission Denied)"]
B -- User Approves --> D["GPS / Wi-Fi / IP Position Lookup"]
D --> E["Success Callback (Latitude & Longitude Coordinates)"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML Geolocation API Example</title>
</head>
<body style="font-family: system-ui, sans-serif; background-color: #0f172a; color: #f8fafc; padding: 2rem;">
<h2>User Location Finder</h2>
<div style="background-color: #1e293b; padding: 1.5rem; border-radius: 8px; max-width: 450px;">
<button id="loc-btn" style="background-color: #2563eb; color: white; padding: 10px 16px; border: none; border-radius: 6px; cursor: pointer;">
Get My Location
</button>
<p id="output" style="margin-top: 1rem; color: #38bdf8;"></p>
</div>
<script>
const btn = document.getElementById("loc-btn");
const output = document.getElementById("output");
btn.addEventListener("click", () => {
if ("geolocation" in navigator) {
output.textContent = "Locating...";
navigator.geolocation.getCurrentPosition(
(pos) => {
const lat = pos.coords.latitude.toFixed(4);
const lng = pos.coords.longitude.toFixed(4);
output.textContent = `Latitude: ${lat}° | Longitude: ${lng}°`;
},
(err) => {
output.textContent = "Unable to retrieve location: " + err.message;
}
);
} else {
output.textContent = "Geolocation is not supported by your browser.";
}
});
</script>
</body>
</html>
enableHighAccuracy: true only when necessary: High accuracy uses device GPS hardware, consuming more battery on mobile devices.Write a JavaScript snippet checking if ("geolocation" in navigator) and calling navigator.geolocation.getCurrentPosition()!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.