JavaScript 如何将geolocation API转换为Promise并获取当前位置

JavaScript 如何将geolocation API转换为Promise并获取当前位置

在本文中,我们将使用Promisify geolocation API将其转换为基于Promise的API。

先决条件: JavaScript Promise

方法: 由于我们知道navigator.geolocation.getCurrentPosition是基于回调的API,因此我们可以轻松地将其转换为基于Promise的API。为了将geolocation API转换为Promise,我们将从浏览器获取用户的当前位置。根据我们是否获取了当前位置,我们将解决或拒绝Promise。

示例:

HTML

<!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;
        }
 
        #gfg {
            color: green;
            font-size: 20px;
            font-weight: bold;
        }
    </style>
</head>
 
<body>
    <h1>GeeksforGeeks</h1>
    <p id="geeks"></p>
 
 
    <button onClick="getLocation()">Get My Location</button>
    <p id="gfg"></p>
 
 
    <script>
        let s = `Promisifying the Geo Location API`;
        document.getElementById("geeks").innerHTML = `
{s}
`;
 
        // 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 = `
           

           <strong>You are Located at :</strong>
          
 
  
          <h5>latitude :{coords.latitude}</h5>
          <h5>longitude : {coords.longitude}</h5>
          `;
                })
                .catch((error) => {
                    // If promise get rejected
                    document.getElementById("gfg")
                        .innerHTML = `{error}
`;
                });
        }
    </script>
</body>
 
</html>

输出:

JavaScript 如何将geolocation API转换为Promise并获取当前位置

示例2: 我们甚至可以简化之前的代码,使其更好。正如我们所知, navigator.geolocation.getCurrentPosition(callback, error) 会自动调用回调函数并传递位置信息。

HTML

<!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;
        }
 
        #gfg {
            color: green;
            font-size: 20px;
            font-weight: bold;
        }
    </style>
</head>
 
<body>
    <h1>GeeksforGeeks</h1>
    <p id="geeks"></p>
 
 
    <button onClick="getLocation()">Get My Location</button>
    <p id="gfg"></p>
 
 
    <script>
        let s = `Promisifying the Geo Location API`;
        document.getElementById("geeks")
        .innerHTML = `
{s}
`;
 
        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 = `
             

                <strong>You are Located at :</strong>
            
 
  
            <h5>latitude :{coords.latitude}</h5>
            <h5>longitude : {coords.longitude}</h5>
            `;
                })
                .catch((error) => {
                    // If promise get rejected
                    document.getElementById("gfg").innerHTML
                             = `{error}
`;
                    // Console.error(error);
                });
        }
    </script>
</body>
 
</html>

输出:

JavaScript 如何将geolocation API转换为Promise并获取当前位置

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程