HTML · HTML APIs · Lesson 50
HTML Geolocation
Get the user's position (with permission).
The Geolocation API is used to get the geographical position of a user. Because this can compromise privacy, the position is not available unless the user approves it.
Example
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
const x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
}
function showError(error) {
x.innerHTML = "Error: " + error.message;
}
</script>
Tip: Geolocation only works on secure contexts (HTTPS). Inside the Try-it frame it may be blocked.
Keep reading “HTML Geolocation”
Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.