One of the most powerful features introduced in HTML5 is the Geolocation API. It allows a web application to request the geographical position (latitude and longitude) of the user's device.
You encounter this constantly on the modern web—for example, when Google Maps asks to “Know your location” or a restaurant website tries to find the “stores nearest you.”
Because physical location is highly sensitive personal data, the Geolocation API is strictly protected by the browser. Your code cannot force the browser to reveal the user's location.
When you trigger the API, the browser will automatically pause and display a security prompt to the user (e.g., “Allow this site to access your location?”). If the user clicks "Block" or "Deny", your code will immediately receive an error.
https:// connection. If you are on standard HTTP, the browser will block the request automatically for privacy reasons.
While this is an HTML5 feature, you actually interact with it using JavaScript via the navigator.geolocation object.
This is the primary method used to request the data. It requires one mandatory argument: a "success" callback function that will run once the coordinates are retrieved.
<button onclick="getLocation()">Find Me!</button>
<p id="demo">Coordinates will appear here...</p>
<script>
const display = document.getElementById("demo");
function getLocation() {
// 1. Check if the browser supports Geolocation
if (navigator.geolocation) {
// 2. Request the location (Triggers the permission popup)
navigator.geolocation.getCurrentPosition(showPosition);
} else {
display.innerHTML = "Geolocation is not supported by your browser.";
}
}
// 3. This function runs automatically once permission is granted
function showPosition(position) {
let lat = position.coords.latitude;
let lon = position.coords.longitude;
display.innerHTML = "Latitude: " + lat + "<br>Longitude: " + lon;
}
</script>
What happens if the user denies permission? What if their device's GPS chip is broken? You should always provide a second "error handling" function to the getCurrentPosition() method.
// Providing a Success Function and an Error Function
navigator.geolocation.getCurrentPosition(showPosition, showError);
// The Error Handler Function
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
display.innerHTML = "You denied the request for Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
display.innerHTML = "Location information is unavailable.";
break;
case error.TIMEOUT:
display.innerHTML = "The request to get user location timed out.";
break;
case error.UNKNOWN_ERROR:
display.innerHTML = "An unknown error occurred.";
break;
}
}