如何在HTML中定位用户的位置?

王林
发布: 2023-08-20 21:45:35
转载
2258 人浏览过

如何在HTML中定位用户的位置?

有时,任务是找到用户的当前位置,然后在网页上显示位置坐标或在地图上显示位置。使用HTML和javascript代码,本文演示了在HTML页面中获取用户当前位置的过程。通过使用两个不同的示例来展示。在第一个示例中,可以获取用户的当前位置,然后在HTML页面上显示位置坐标。在第二个示例中,使用开源的Leaflet地图库来获取并在地图上显示用户的当前位置。

示例1:查找用户的当前位置并在html页面上显示位置坐标。

Code Explanation and Design Steps

步骤 1 − 创建一个 HTML 文件并开始编写代码。

第二步 - 创建一个标签

并将其设置为显示位置坐标。

步骤 3 - 创建一个按钮,并在按钮点击时调用函数 getYourLoc()。

第四步 - 在<script>标签中编写代码,并创建两个函数getYourLoc()和showMyPos(pos)。</script>

Step 5 − Write the javascript code in getYourLoc() to find the current location using navigator.geolocation.getCurrentPosition() and then call showMyPos(pos).

第6步 - 将位置添加到之前创建的

标签中,使用showMyPos(pos)。检查结果。

Important file used − locationfile.html

Code For parentFolderFile.html:

的中文翻译为:

parentFolderFile.html的代码:

<!DOCTYPE html>
<html>
   <body>
      <p>Show My Location Coordinates</p>
      <button onclick="getYourLoc()">Get the location coordinates</button>
      <p id="showloc"></p> 
      <script>
      var x = document.getElementById("showloc");
      function getYourLoc() {
         if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showMyPos);
         } else {
            x.innerHTML = "No support for this in the browser.";
         }
      }
      function showMyPos(pos) {
         x.innerHTML = "My Latitude is : " + pos.coords.latitude +
         "<br>My Longitude is : " + pos.coords.longitude;
      }
      </script>
   </body>
</html>
登录后复制

Viewing The Result

要查看结果,请在浏览器中打开loactionfile.html文件。现在点击按钮以查找用户的当前位置。坐标将显示在html页面上。

示例2:查找用户当前位置并在地图上显示位置坐标。

Code Explanation and Design Steps

步骤 1 − 创建一个 HTML 文件并开始编写代码。

第二步 - 创建一个标签

并将其设置为显示位置坐标。

步骤 3 - 创建一个按钮,并在按钮点击时调用函数 getYourLoc()。

Step 4 − Inside the

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!