Open In App

HTML Geolocation getCurrentPosition() Method

In this article, we will know HTML Geolocation getCurrentPosition() Method, various parameters, & their implementation through the examples. HTML5 provides us 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.

The getCurrentPosition() method is used for getting the current location of the user.



Syntax:

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

 



Parameter values:

Please refer to the HTML Geolocation article for the various properties, methods & their implementation in detail.

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




<!DOCTYPE html>
<html>
  
<head>
    <title>Get Current Position</title>
</head>
  
<body>
    <h2>Welcome To GFG</h2>
    <div>
        <button onclick="geolocator()">click me</button>
        <p id="paraGraph"></p>
  
    </div>
    <script>
        var paraGraph = document.getElementById("paraGraph");
        var user_loc = navigator.geolocation;
      
        function geolocator() {
            if(user_loc) {
                user_loc.getCurrentPosition(success);
            } else {
                "Your browser doesn't support geolocation API";
            }
        }
      
        function success(data) {
            var lat = data.coords.latitude;
            var long = data.coords.longitude;
            paraGraph.innerHTML = "Latitude: " 
            + lat 
            + "<br>Longitude: " 
            + long;
        }
    </script>
</body>
  
</html>

Output:

Getting the user’s current geolocation. 

Example 2: To Display timestamp and Accuracy.




<!DOCTYPE html>
<html>
  
<head>
    <title>Get Current Location</title>
</head>
  
<body>
    <h2>Welcome To GFG</h2>
    <div>
        <button onclick="geolocator()">click me</button>
        <p id="paraGraph"></p>
  
    </div>
    <script>
        var paraGraph = document.getElementById("paraGraph");
        var user_loc = navigator.geolocation;
      
        function geolocator() {
            if(user_loc) {
                user_loc.getCurrentPosition(success);
            } else {
                "Your browser doesn't support geolocation API";
            }
        }
      
        function success(data) {
            var accu = data.coords.accuracy;
            var tmstmp = data.timestamp;
            paraGraph.innerHTML = "Accuracy: " 
            + accu 
            + "<br>Time Stamp: " 
            + tmstmp;
        }
    </script>
</body>
  
</html>

Output:

Getting the timestamp and Accuracy of a user

Supported Browsers:


Article Tags :