|
Answer» In HTML5 the Geolocation API was introduced. With the help of it, we can get the user location very easily through a browser. We can get the current position of the user through the navigator.geolocation.getCurrentPosition() method. It takes one required and TWO optional arguments. The required ARGUMENT is the success argument and the optional ONES are an error, options. - success - The main callback function to show our coordinates. Only we have access to Position object, from which we can take latitude and longitude of the user
- error - An optional callback function, which will show the error message in case of any error.
- options- An optional object in which we can give enableHighAccuracy, timeout, and maximumAge.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Geolocation Demo</title>
<script>
window.onload = function () {
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
let loc = document.getElementById("my_location");
var crd = pos.coords;
loc.innerHTML = `Latitude : ${crd.latitude}, Longitude: ${crd.longitude}, More or less ${crd.accuracy} meters.`;
}
function error(err) {
let loc = document.getElementById("my_location");
loc.innerHTML = `ERROR(${err.code}): ${err.message}`;
}
navigator.geolocation.getCurrentPosition(success, error, options);
};
</script>
</head>
<body>
<h1>Geolocation Demo</h1>
<p>Grant permissions to know your location.</p>
<p>Your current position is:</p>
<div id="my_location"></div>
</body>
</html>Open this file in the browser and you will get a pop-up, asking to Allow to use current location. Click on “Allow” and you will get your current location. Close and open the demo.html again. This TIME click on “Don’t Allow” and you will get the error message which has been shown by the error function.
|