The HTML Geolocation API is used to get the geographical position of a user. (if they approves)
The getCurrentPosition() method is used to return the user's position. It can be accessed from the navigator object
The example below returns the latitude and longitude of the user's position:
const myElement = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
myElement.innerHTML = "Geolocation is not supported by this browser.";
}
}
getLocation();
//show position in HTML
function showPosition(position) {
myElement.innerHTML = `Latitude: ${position.coords.latitude}
Longitude: ${position.coords.longitude}`;
}
The example above is a very basic Geolocation script, with no error handling. Other examples in W3Schools