Thursday, August 28, 2025
HomeLanguagesJavascriptHow to Promisify geolocation API to get current position using JavaScript ?

How to Promisify geolocation API to get current position using JavaScript ?

In this article, we are going to use Promisify geolocation API into Promise-based API.

Prerequisite: JavaScript Promise 

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.

Example: 

HTML




<!DOCTYPE html>
<html>
 
<head>
    <meta charset="UTF-8" />
 
    <style>
        body {
            text-align: center;
        }
 
        h1 {
            color: green;
        }
 
        h5 {
            color: black;
        }
 
        #neveropen {
            font-size: 16px;
            font-weight: bold;
        }
 
        #gfg {
            color: green;
            font-size: 20px;
            font-weight: bold;
        }
    </style>
</head>
 
<body>
    <h1>neveropen</h1>
    <p id="neveropen"></p>
 
 
    <button onClick="getLocation()">Get My Location</button>
    <p id="gfg"></p>
 
 
    <script>
        let s = `Promisifying the Geo Location API`;
        document.getElementById("neveropen").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("gfg")
                        .innerHTML = `
<p>${error}</p>
`;
                });
        }
    </script>
</body>
 
</html>


Output:

Promisify the geoLocation API

Example 2: We can even simplify the previous code, to make it better. As we know the navigator.geolocation.getCurrentPosition(callback, error) automatically calls the call-back function and passes the position.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <meta charset="UTF-8" />
    <style>
        body {
            text-align: center;
        }
 
        h1 {
            color: green;
        }
 
        h5 {
            color: black;
        }
 
        #neveropen {
            font-size: 16px;
            font-weight: bold;
        }
 
        #gfg {
            color: green;
            font-size: 20px;
            font-weight: bold;
        }
    </style>
</head>
 
<body>
    <h1>neveropen</h1>
    <p id="neveropen"></p>
 
 
    <button onClick="getLocation()">Get My Location</button>
    <p id="gfg"></p>
 
 
    <script>
        let s = `Promisifying the Geo Location API`;
        document.getElementById("neveropen")
        .innerHTML = `
<p>${s}</p>
`;
 
        let getLocationPromise = () => {
            return new Promise(function (resolve, reject) {
 
                // Automatically passes the position
                // to the callback
                navigator.geolocation
                    .getCurrentPosition(resolve, reject);
            });
        };
        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("gfg").innerHTML
                             = `
<p>${error}</p>
`;
                    // Console.error(error);
                });
        }
    </script>
</body>
 
</html>


Output:

Promisify the geoLocation API

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32244 POSTS0 COMMENTS
Milvus
80 POSTS0 COMMENTS
Nango Kala
6615 POSTS0 COMMENTS
Nicole Veronica
11787 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11831 POSTS0 COMMENTS
Shaida Kate Naidoo
6726 POSTS0 COMMENTS
Ted Musemwa
7008 POSTS0 COMMENTS
Thapelo Manthata
6683 POSTS0 COMMENTS
Umr Jansen
6696 POSTS0 COMMENTS