Geolocation API HTML
Geolocation API HTML
❮ PreviousNext ❯
Since this can compromise privacy, the position is not available unless the user
approves it.
Try It
Note: Geolocation is most accurate for devices with GPS, like smartphones.
Browser Support
The numbers in the table specify the first browser version that fully supports
Geolocation.
API
The example below returns the latitude and longitude of the user's position:
Example
<script>
const x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
Try it Yourself »
Example explained:
The example above is a very basic Geolocation script, with no error handling.
ADVERTISEMENT
Example
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
Try it Yourself »
Location-specific Information
This page has demonstrated how to show a user's position on a map.
coords.altitude The altitude in meters above the mean sea level (returned if avail
The example below shows the watchPosition() method. You need an accurate
GPS device to test this (like smartphone):
Example
<script>
const x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
Try it Yourself »