The Geolocation API allows websites to access the current location of a user (latitude, longitude, accuracy, etc.). It is commonly used in maps, delivery apps, weather apps, and location-based services.
Important
The browser asks the user for permission. If granted, it returns the device’s coordinates.
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
<!DOCTYPE html>
<html>
<body>
<h2>Get User Location</h2>
<button onclick="getLocation()">Get My Location</button>
<p id="output"></p>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
document.getElementById("output").innerHTML =
"Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
document.getElementById("output").innerHTML =
"Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
message = "User denied the request for Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
message = "Location information is unavailable.";
break;
case error.TIMEOUT:
message = "The request to get user location timed out.";
break;
case error.UNKNOWN_ERROR:
message = "An unknown error occurred.";
break;
}
document.getElementById("output").innerHTML = message;
}
</script>
</body>
</html>
navigator.geolocation.watchPosition(position => {
console.log("Latitude: " + position.coords.latitude);
console.log("Longitude: " + position.coords.longitude);
});
watchPosition() continuously updates location (useful for navigation apps).
| Property | Description |
|---|---|
coords.latitude |
User’s latitude |
coords.longitude |
User’s longitude |
coords.accuracy |
Accuracy in meters |
coords.altitude |
Height above sea level |
coords.speed |
Speed of the device |
timestamp |
Time the location was taken |
| Error Code | Meaning |
|---|---|
| PERMISSION_DENIED | User blocked location access |
| POSITION_UNAVAILABLE | Cannot determine location |
| TIMEOUT | Took too long to get location |
| UNKNOWN_ERROR | An unknown error occurred |
<!DOCTYPE html>
<html>
<body>
<h2>Show My Location on Google Maps</h2>
<button onclick="showMap()">Open Map</button>
<script>
function showMap() {
navigator.geolocation.getCurrentPosition(function(position) {
const url =
"https://www.google.com/maps?q=" +
position.coords.latitude + "," +
position.coords.longitude;
window.open(url, "_blank");
});
}
</script>
</body>
</html>