首页  >  文章  >  web前端  >  小强的HTML5移动开发之路(18)——HTML5地理定位

小强的HTML5移动开发之路(18)——HTML5地理定位

黄舟
黄舟原创
2017-01-22 13:56:201384浏览

在前面的《小强的HTML5移动开发之路(2)——HTML5的新特性》中介绍了关于HTML5的地理定位功能,这一篇我们来详细了解一下怎么使用该功能。

Html5 Geolocation API用于获得用户的地理位置。

鉴于该特性可能侵犯用户的隐私,除非用户同意,否则用户位置信息是不可用的,在使用该功能的时候浏览器会弹出提醒框。

一、地理定位的几种方式

IP地址、GPS、Wifi、GSM/CDMA

二、地理位置获取流程


1、用户打开需要获取地理位置的web应用。

2、应用向浏览器请求地理位置,浏览器弹出询问,询问用户是否共享地理位置。

3、假设用户允许,浏览器从设别查询相关信息。

4、浏览器将相关信息发送到一个信任的位置服务器,服务器返回具体的地理位置。


三、浏览器的支持

IE9.0+、FF3.5+、Safari5.0+、Chrome5.0+、Opera10.6+ 支持地理定位。

注释:对于拥有 GPS 的设备,比如 iPhone(IPhone3.0+、Android2.0+),地理定位更加精确。

四、HTML5中地理位置定位的方法


GeolocationAPI存在于navigator对象中,只包含3个方法:

1、getCurrentPosition   //当前位置

2、watchPosition           //监视位置

3、clearWatch               //清除监视

五、地理定位方法getCurrentPosition()

<!DOCTYPE html>  
<html>  
<body>  
    <p id="demo">点击这个按钮,获得您的坐标:</p>  
    <button onclick="getLocation()">试一下</button>  
    <script>  
        var x=document.getElementById("demo");  
        function getLocation(){  
          if (navigator.geolocation){  //判断是否支持地理定位  
              //如果支持,则运行getCurrentPosition()方法。  
              navigator.geolocation.getCurrentPosition(showPosition);  
          }else{  
              //如果不支持,则向用户显示一段消息  
              x.innerHTML="Geolocation is not supported by this browser.";  
          }  
        }  
  
        //获取经纬度并显示  
        function showPosition(position){  
            x.innerHTML="Latitude: " + position.coords.latitude +   
            "<br />Longitude: " + position.coords.longitude;    
        }  
    </script>  
</body>  
</html>

737.jpg

getCurrentPosition(success,error,option)方法最多可以有三个参数:

getCurrentPosition()方法第一个参数回调一个showPosition()函数并将位置信息传递给该函数,从该函数中获取位置信息并显示,

getCurrentPostion()方法第二个参数用于处理错误信息,它是获取位置信息失败的回调函数

getCurrentPostion()方法第三个参数是配置项,该参数是一个对象,影响了获取位置的细节。

<!DOCTYPE html>  
<html>  
<body>  
    <p id="demo">点击这个按钮,获得您的坐标:</p>  
    <button onclick="getLocation()">试一下</button>  
    <script>  
        var x=document.getElementById("demo");  
        function getLocation(){  
          if (navigator.geolocation){  //判断是否支持地理定位  
              //如果支持,则运行getCurrentPosition()方法。  
              navigator.geolocation.getCurrentPosition(showPosition,showError);  
          }else{  
              //如果不支持,则向用户显示一段消息  
              x.innerHTML="Geolocation is not supported by this browser.";  
          }  
        }  
  
        //获取经纬度并显示  
        function showPosition(position){  
            x.innerHTML="Latitude: " + position.coords.latitude +   
            "<br />Longitude: " + position.coords.longitude;    
        }  
  
        //错误处理函数  
        function showError(error){  
          switch(error.code)  //错误码   
            {  
            case error.PERMISSION_DENIED:  //用户拒绝  
              x.innerHTML="User denied the request for Geolocation."  
              break;  
            case error.POSITION_UNAVAILABLE:  //无法提供定位服务  
              x.innerHTML="Location information is unavailable."  
              break;  
            case error.TIMEOUT:  //连接超时  
              x.innerHTML="The request to get user location timed out."  
              break;  
            case error.UNKNOWN_ERROR:  //未知错误  
              x.innerHTML="An unknown error occurred."  
              break;  
            }  
         }  
    </script>  
</body>  
</html>

六、在Google地图中显示结果

<!DOCTYPE html>  
<html>  
<body>  
    <p id="demo">点击这个按钮,获得您的位置:</p>  
    <button onclick="getLocation()">试一下</button>  
    <div id="mapholder"></div>  
        <script src="http://maps.google.com/maps/api/js?sensor=false"></script>  
        <script>  
            var x=document.getElementById("demo");  
                function getLocation(){  
                   if (navigator.geolocation){  
                     navigator.geolocation.getCurrentPosition(showPosition,showError);  
                    }else{  
                        x.innerHTML="Geolocation is not supported by this browser.";  
                    }  
                }  
  
                function showPosition(position){  
                      lat=position.coords.latitude;  
                      lon=position.coords.longitude;  
                      latlon=new google.maps.LatLng(lat, lon)  
                      mapholder=document.getElementById(&#39;mapholder&#39;)  
                      mapholder.style.height=&#39;250px&#39;;  
                      mapholder.style.width=&#39;500px&#39;;  
  
                      var myOptions={  
                          center:latlon,zoom:14,  
                          mapTypeId:google.maps.MapTypeId.ROADMAP,  
                          mapTypeControl:false,  
                          navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}  
                      };  
                      var map=new google.maps.Map(document.getElementById("mapholder"),myOptions);  
                      var marker=new google.maps.Marker({position:latlon,map:map,title:"You are here!"});  
                 }  
  
                function showError(error){  
                      switch(error.code){  
                        case error.PERMISSION_DENIED:  
                          x.innerHTML="User denied the request for Geolocation."  
                          break;  
                        case error.POSITION_UNAVAILABLE:  
                          x.innerHTML="Location information is unavailable."  
                          break;  
                        case error.TIMEOUT:  
                          x.innerHTML="The request to get user location timed out."  
                          break;  
                        case error.UNKNOWN_ERROR:  
                          x.innerHTML="An unknown error occurred."  
                          break;  
                        }  
                }  
        </script>  
</body>  
</html>

738.jpg

七、在百度地图中显示结果

1、去百度开发者获取地图显示密钥

http://developer.baidu.com/map/jshome.htm

739.jpg

<!DOCTYPE html>  
<html>  
<body>  
    <p id="demo">点击这个按钮,获得您的位置:</p>  
    <button onclick="getLocation()">试一下</button>  
    <div id="mapholder" style="width:600px;height:500px;"></div>  
        <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=你自己的密钥"></script>  
        <script>  
            var x=document.getElementById("demo");  
                function getLocation(){  
                   if (navigator.geolocation){  
                     navigator.geolocation.getCurrentPosition(showPosition,showError);  
                    }else{  
                        x.innerHTML="Geolocation is not supported by this browser.";  
                    }  
                }  
  
                function showPosition(position){  
                    //alert(position.coords.longitude + " ___ " + position.coords.latitude);  
                       
                    // 百度地图API功能  
                    var map = new BMap.Map("mapholder");            // 创建Map实例  
                    var point = new BMap.Point(position.coords.longitude, position.coords.latitude);    // 创建点坐标  
                    map.centerAndZoom(point,15);                     // 初始化地图,设置中心点坐标和地图级别。  
                    map.enableScrollWheelZoom();   
                 }  
  
                function showError(error){  
                      switch(error.code){  
                        case error.PERMISSION_DENIED:  
                          x.innerHTML="User denied the request for Geolocation."  
                          break;  
                        case error.POSITION_UNAVAILABLE:  
                          x.innerHTML="Location information is unavailable."  
                          break;  
                        case error.TIMEOUT:  
                          x.innerHTML="The request to get user location timed out."  
                          break;  
                        case error.UNKNOWN_ERROR:  
                          x.innerHTML="An unknown error occurred."  
                          break;  
                        }  
                }  
        </script>  
</body>  
</html>

注意:如果拷贝上面代码,请将“你自己的密钥”替换为在百度开发者中心申请的密钥

740.jpg


可以看到Google Map 和百度地图的定位参考不同,所以用ip定位误差很大。

八、getCurrentPosition()方法—返回数据


若成功,则 getCurrentPosition() 方法返回对象。始终会返回 latitude、longitude 以及 accuracy 属性。如果可用,则会返回其他下面的属性。


属性

描述

coords.latitude    十进制数的纬度    

coords.longitude    十进制数的经度    

coords.accuracy    位置精度    

coords.altitude    海拔,海平面以上以米计    

coords.altitudeAccuracy    位置的海拔精度    

coords.heading    方向,从正北开始以度计    

coords.speed    速度,以米/每秒计    

timestamp    响应的日期/时间    



还可以获得地理位置(只有firefox支持)


p.address.country   国家

p.address.region    省份

p.address.city          城市

九、监视位置(移动设备中)


watchPosition() - 返回用户的当前位置,并继续返回用户移动时的更新位置(就像汽车上的 GPS)。

clearWatch() - 停止 watchPosition() 方法

下面的例子展示 watchPosition() 方法

watchPosition像一个追踪器与clearWatch成对。

watchPosition与clearWatch有点像setInterval和clearInterval的工作方式。

varwatchPositionId =navigator.geolocation.watchPosition(success_callback,error_callback,options);

navigator.geolocation.clearWatch(watchPositionId );

<!DOCTYPE html>  
<html>  
<body>  
<p id="demo">点击这个按钮,获得您的坐标:</p>  
<button onclick="getLocation()">试一下</button>  
<script>  
var x=document.getElementById("demo");  
function getLocation()  
  {  
  if (navigator.geolocation)  
    {  
    navigator.geolocation.watchPosition(showPosition);  
    }  
  else{x.innerHTML="Geolocation is not supported by this browser.";}  
  }  
function showPosition(position)  
  {  
  x.innerHTML="Latitude: " + position.coords.latitude +   
  "<br />Longitude: " + position.coords.longitude;      
  }  
</script>  
</body>  
</html>

以上就是 小强的HTML5移动开发之路(18)——HTML5地理定位的内容,更多相关内容请关注PHP中文网(www.php.cn)!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn