如何使用 HTML5 地理位置信息查找位置?


HTML5 地理位置信息 API 允许你与你喜爱的网站共享你的位置。JavaScript 能够获取你的纬度和经度并发送到后端 Web 服务,并执行诸如查找当地企业或在地图上显示你的位置等时髦的与位置相关的操作。

地理位置信息 API 与全局导航器对象(即地理位置对象)的新属性一起使用。

getCurrentPosition 方法会检索设备当前的地理位置。位置表示为一组地理坐标以及有关航向和速度的信息。位置信息会返回到一个位置对象。

示例

你可以尝试运行下列代码来查找当前位置

<!DOCTYPE HTML>
<html>
   <head>
      <script type = "text/javascript">
         function showLocation(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            alert("Latitude : " + latitude + " Longitude: " + longitude);
         }
         function errorHandler(err) {
            if(err.code == 1) {
               alert("Error: Access is denied!");
            }
            else if( err.code == 2) {
               alert("Error: Position is unavailable!");
            }
         }
         function getLocation(){
            if(navigator.geolocation){
            // timeout at 60000 milliseconds (60 seconds)
               var options = {timeout:60000};
               navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);
            } else {
               alert("Sorry, browser does not support geolocation!");
            }
         }
      </script>
   </head>
   <body>
      <form>
         <input type = "button" onclick = "getLocation();" value = "Get Location"/>
      </form>
   </body>
</html>

更新日期:2020 年 1 月 10 日

194 次浏览

开启您的职业

通过完成课程获得认证

开始使用
广告
© . All rights reserved.