HTML Geolocation API
The HTML Geolocation API is used to get the geographical position of a user. For privacy reasons, this requires user permission.
Locate the User's Position
The navigator.geolocation.getCurrentPosition() method is used to get the user's position. If the user gives permission, the browser will use the best available method (GPS, WiFi, etc.) to determine the location and return coordinates (latitude and longitude) in a callback function.
Example: Getting Geolocation
html
<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>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>Test Yourself with an Exercise
Which JavaScript method is used to get the user's current position?