Open In App

How to locate the user’s position in HTML ?

In this article, we will discuss how to locate the user’s position in HTML.

Approach: The getCurrentPosition() method is used to locate the current location of the user. HTML5 provides us with the Geolocation API which helps us to identify the geographic location of the user. The Geolocation API gives the latitude and longitude of the user’s current location which are further sent to the backend using JavaScript and then the current location of the user is shown on the website.



Syntax:

navigator.geolocation.getCurrentPosition(success, error, options);

Parameters: It has three parameters as mentioned above and described below:



Example: The below example illustrate the Geolocation getCurrentPosition() Method by checking the user’s geolocation.




<!DOCTYPE html>
<html>
 
<body>
    <h1 style="color: green">Welcome To GFG</h1>
    <h3>How to locate the user's position in HTML?</h3>
    <div>
        <button onclick="geolocator()">
            Click to get location
        </button>
        <p id="paraGraph"></p>
    </div>
    <script>
        let paraGraph = document.getElementById("paraGraph");
        let user_loc = navigator.geolocation;
        function geolocator() {
            if (user_loc) {
                user_loc.getCurrentPosition(success);
            } else {
                "Your browser doesn't support geolocation API";
            }
        }
        function success(data) {
            let lat = data.coords.latitude;
            let long = data.coords.longitude;
            paraGraph.innerHTML = "Latitude: "
                + lat
                + "<br>Longitude: "
                + long;
        }
    </script>
</body>
</html>

Output:

Example 2: In this example, we will get the accuracy and timestamp of the location.




<!DOCTYPE html>
<html>
 
<body>
    <h1 style="color: green">Welcome To GFG</h1>
    <div>
        <button onclick="geolocator()">
            Click to get accuracy and timestamp
        </button>
        <p id="paraGraph"></p>
    </div>
    <script>
        let paraGraph = document.getElementById("paraGraph");
        let user_loc = navigator.geolocation;
        function geolocator() {
            if (user_loc) {
                user_loc.getCurrentPosition(success);
            } else {
                "Your browser doesn't support geolocation API";
            }
        }
        function success(data) {
            let accu = data.coords.accuracy;
            let tmstmp = data.timestamp;
            paraGraph.innerHTML = "Accuracy: "
                + accu
                + "<br>Time Stamp: "
                + tmstmp;
        }
    </script>
</body>
 
</html>

Output:


Article Tags :