How to Promisify location API to get current position using JavaScript

Approach: As we know the navigator.geolocation.getCurrentPosition is a callback-based API, so we can easily convert it into a Promise-based API. To promisify the geolocation API, we will get the user’s current position from the browser. We will either resolve the promise or reject the promise based upon, either we get the current position.

<!DOCTYPE html>
<html>
 
<head>
    <meta charset="UTF-8" />
 
    <style>
        body {
            text-align: center;
        }
 
        h1 {
            color: green;
        }
 
        h5 {
            color: black;
        }
 
        #geeks {
            font-size: 16px;
            font-weight: bold;
        }
 
        #test{
            color: green;
            font-size: 20px;
            font-weight: bold;
        }
    </style>
</head>
 
<body>
    <h1>Test</h1>
    <p id="test"></p>
 
 
    <button onClick="getLocation()">Get My Location</button>
    <p id="test1"></p>
 
 
    <script>
        let s = `Promisifying the Geo Location API`;
        document.getElementById("geeks").innerHTML = `
<p>${s}</p>
`;
 
        // Logic start here
        let getLocationPromise = () => {
            return new Promise(function (resolve, reject) {
 
                // Promisifying the geolocation API
                navigator.geolocation.getCurrentPosition(
                    (position) => resolve(position),
                    (error) => reject(error)
                );
            });
        };
 
        function getLocation() {
            getLocationPromise()
                .then((res) => {
                     
                    // If promise get resolved
                    const { coords } = res;
                    document.getElementById("gfg").innerHTML = `
           
<p>
           <strong>You are Located at :</strong>
          </p>
 
  
          <h5>latitude : ${coords.latitude}</h5>
          <h5>longitude : ${coords.longitude}</h5>
          `;
                })
                .catch((error) => {
                    // If promise get rejected
                    document.getElementById("test1")
                        .innerHTML = `
<p>${error}</p>
`;
                });
        }
    </script>
</body>
 
</html>

Leave a comment

Your email address will not be published. Required fields are marked *