小強的HTML5移動開發之路(18)——HTML5地理定位

來自:http://blog.csdn.net/dawanganban/article/details/18192091javascript

在前面的《小強的HTML5移動開發之路(2)——HTML5的新特性》中介紹了關於HTML5的地理定位功能,這一篇咱們來詳細瞭解一下怎麼使用該功能。html

HTML5 Geolocation API用於得到用戶的地理位置。java

鑑於該特性可能侵犯用戶的隱私,除非用戶贊成,不然用戶位置信息是不可用的,在使用該功能的時候瀏覽器會彈出提醒框。git

1、地理定位的幾種方式web

IP地址、GPS、Wifi、GSM/CDMAapi

2、地理位置獲取流程瀏覽器

一、用戶打開須要獲取地理位置的web應用。服務器

二、應用向瀏覽器請求地理位置,瀏覽器彈出詢問,詢問用戶是否共享地理位置。ide

三、假設用戶容許,瀏覽器從設別查詢相關信息。函數

四、瀏覽器將相關信息發送到一個信任的位置服務器,服務器返回具體的地理位置。

3、瀏覽器的支持

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

註釋:對於擁有 GPS 的設備,好比 iPhone(IPhone3.0+、Android2.0+),地理定位更加精確。

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

GeolocationAPI存在於navigator對象中,只包含3個方法:

一、getCurrentPosition   //當前位置

二、watchPosition           //監視位置

三、clearWatch               //清除監視

5、地理定位方法getCurrentPosition()

  1. <!DOCTYPE html>  
  2. <html>  
  3. <body>  
  4.     <p id="demo">點擊這個按鈕,得到您的座標:</p>  
  5.     <button onclick="getLocation()">試一下</button>  
  6.     <script>  
  7.         var x=document.getElementById("demo");  
  8.         function getLocation(){  
  9.           if (navigator.geolocation){  //判斷是否支持地理定位  
  10.               //若是支持,則運行getCurrentPosition()方法。  
  11.               navigator.geolocation.getCurrentPosition(showPosition);  
  12.           }else{  
  13.               //若是不支持,則向用戶顯示一段消息  
  14.               x.innerHTML="Geolocation is not supported by this browser.";  
  15.           }  
  16.         }  
  17.   
  18.         //獲取經緯度並顯示  
  19.         function showPosition(position){  
  20.             x.innerHTML="Latitude: " + position.coords.latitude +   
  21.             "<br />Longitude: " + position.coords.longitude;    
  22.         }  
  23.     </script>  
  24. </body>  
  25. </html>  

getCurrentPosition(success,error,option)方法最多能夠有三個參數:

getCurrentPosition()方法第一個參數回調一個showPosition()函數並將位置信息傳遞給該函數,從該函數中獲取位置信息並顯示,

getCurrentPostion()方法第二個參數用於處理錯誤信息,它是獲取位置信息失敗的回調函數

getCurrentPostion()方法第三個參數是配置項,該參數是一個對象,影響了獲取位置的細節。

  1. <!DOCTYPE html>  
  2. <html>  
  3. <body>  
  4.     <p id="demo">點擊這個按鈕,得到您的座標:</p>  
  5.     <button onclick="getLocation()">試一下</button>  
  6.     <script>  
  7.         var x=document.getElementById("demo");  
  8.         function getLocation(){  
  9.           if (navigator.geolocation){  //判斷是否支持地理定位  
  10.               //若是支持,則運行getCurrentPosition()方法。  
  11.               navigator.geolocation.getCurrentPosition(showPosition,showError);  
  12.           }else{  
  13.               //若是不支持,則向用戶顯示一段消息  
  14.               x.innerHTML="Geolocation is not supported by this browser.";  
  15.           }  
  16.         }  
  17.   
  18.         //獲取經緯度並顯示  
  19.         function showPosition(position){  
  20.             x.innerHTML="Latitude: " + position.coords.latitude +   
  21.             "<br />Longitude: " + position.coords.longitude;    
  22.         }  
  23.   
  24.         //錯誤處理函數  
  25.         function showError(error){  
  26.           switch(error.code)  //錯誤碼   
  27.             {  
  28.             case error.PERMISSION_DENIED:  //用戶拒絕  
  29.               x.innerHTML="User denied the request for Geolocation."  
  30.               break;  
  31.             case error.POSITION_UNAVAILABLE:  //沒法提供定位服務  
  32.               x.innerHTML="Location information is unavailable."  
  33.               break;  
  34.             case error.TIMEOUT:  //鏈接超時  
  35.               x.innerHTML="The request to get user location timed out."  
  36.               break;  
  37.             case error.UNKNOWN_ERROR:  //未知錯誤  
  38.               x.innerHTML="An unknown error occurred."  
  39.               break;  
  40.             }  
  41.          }  
  42.     </script>  
  43. </body>  
  44. </html>  

6、在Google地圖中顯示結果

  1. <!DOCTYPE html>  
  2. <html>  
  3. <body>  
  4.     <p id="demo">點擊這個按鈕,得到您的位置:</p>  
  5.     <button onclick="getLocation()">試一下</button>  
  6.     <div id="mapholder"></div>  
  7.         <script src="http://maps.google.com/maps/api/js?sensor=false"></script>  
  8.         <script>  
  9.             var x=document.getElementById("demo");  
  10.                 function getLocation(){  
  11.                    if (navigator.geolocation){  
  12.                      navigator.geolocation.getCurrentPosition(showPosition,showError);  
  13.                     }else{  
  14.                         x.innerHTML="Geolocation is not supported by this browser.";  
  15.                     }  
  16.                 }  
  17.   
  18.                 function showPosition(position){  
  19.                       lat=position.coords.latitude;  
  20.                       lon=position.coords.longitude;  
  21.                       latlon=new google.maps.LatLng(lat, lon)  
  22.                       mapholder=document.getElementById('mapholder')  
  23.                       mapholder.style.height='250px';  
  24.                       mapholder.style.width='500px';  
  25.   
  26.                       var myOptions={  
  27.                           center:latlon,zoom:14,  
  28.                           mapTypeId:google.maps.MapTypeId.ROADMAP,  
  29.                           mapTypeControl:false,  
  30.                           navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}  
  31.                       };  
  32.                       var map=new google.maps.Map(document.getElementById("mapholder"),myOptions);  
  33.                       var marker=new google.maps.Marker({position:latlon,map:map,title:"You are here!"});  
  34.                  }  
  35.   
  36.                 function showError(error){  
  37.                       switch(error.code){  
  38.                         case error.PERMISSION_DENIED:  
  39.                           x.innerHTML="User denied the request for Geolocation."  
  40.                           break;  
  41.                         case error.POSITION_UNAVAILABLE:  
  42.                           x.innerHTML="Location information is unavailable."  
  43.                           break;  
  44.                         case error.TIMEOUT:  
  45.                           x.innerHTML="The request to get user location timed out."  
  46.                           break;  
  47.                         case error.UNKNOWN_ERROR:  
  48.                           x.innerHTML="An unknown error occurred."  
  49.                           break;  
  50.                         }  
  51.                 }  
  52.         </script>  
  53. </body>  
  54. </html>  


7、在百度地圖中顯示結果

一、去百度開發者獲取地圖顯示密鑰

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


  1. <!DOCTYPE html>  
  2. <html>  
  3. <body>  
  4.     <p id="demo">點擊這個按鈕,得到您的位置:</p>  
  5.     <button onclick="getLocation()">試一下</button>  
  6.     <div id="mapholder" style="width:600px;height:500px;"></div>  
  7.         <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=你本身的密鑰"></script>  
  8.         <script>  
  9.             var x=document.getElementById("demo");  
  10.                 function getLocation(){  
  11.                    if (navigator.geolocation){  
  12.                      navigator.geolocation.getCurrentPosition(showPosition,showError);  
  13.                     }else{  
  14.                         x.innerHTML="Geolocation is not supported by this browser.";  
  15.                     }  
  16.                 }  
  17.   
  18.                 function showPosition(position){  
  19.                     //alert(position.coords.longitude + " ___ " + position.coords.latitude);  
  20.                        
  21.                     // 百度地圖API功能  
  22.                     var map = new BMap.Map("mapholder");            // 建立Map實例  
  23.                     var point = new BMap.Point(position.coords.longitude, position.coords.latitude);    // 建立點座標  
  24.                     map.centerAndZoom(point,15);                     // 初始化地圖,設置中心點座標和地圖級別。  
  25.                     map.enableScrollWheelZoom();   
  26.                  }  
  27.   
  28.                 function showError(error){  
  29.                       switch(error.code){  
  30.                         case error.PERMISSION_DENIED:  
  31.                           x.innerHTML="User denied the request for Geolocation."  
  32.                           break;  
  33.                         case error.POSITION_UNAVAILABLE:  
  34.                           x.innerHTML="Location information is unavailable."  
  35.                           break;  
  36.                         case error.TIMEOUT:  
  37.                           x.innerHTML="The request to get user location timed out."  
  38.                           break;  
  39.                         case error.UNKNOWN_ERROR:  
  40.                           x.innerHTML="An unknown error occurred."  
  41.                           break;  
  42.                         }  
  43.                 }  
  44.         </script>  
  45. </body>  
  46. </html>  

注意:若是拷貝上面代碼,請將「你本身的密鑰」替換爲在百度開發者中心申請的密鑰


能夠看到Google Map 和百度地圖的定位參考不一樣,因此用ip定位偏差很大。

8、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          城市

9、監視位置(移動設備中)

watchPosition() - 返回用戶的當前位置,並繼續返回用戶移動時的更新位置(就像汽車上的 GPS)。

clearWatch() - 中止 watchPosition() 方法

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

watchPosition像一個追蹤器與clearWatch成對。

watchPositionclearWatch有點像setIntervalclearInterval的工做方式。

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

navigator.geolocation.clearWatch(watchPositionId );

  1. <!DOCTYPE html>  
  2. <html>  
  3. <body>  
  4. <p id="demo">點擊這個按鈕,得到您的座標:</p>  
  5. <button onclick="getLocation()">試一下</button>  
  6. <script>  
  7. var x=document.getElementById("demo");  
  8. function getLocation()  
  9.   {  
  10.   if (navigator.geolocation)  
  11.     {  
  12.     navigator.geolocation.watchPosition(showPosition);  
  13.     }  
  14.   else{x.innerHTML="Geolocation is not supported by this browser.";}  
  15.   }  
  16. function showPosition(position)  
  17.   {  
  18.   x.innerHTML="Latitude: " + position.coords.latitude +   
  19.   "<br />Longitude: " + position.coords.longitude;      
  20.   }  
  21. </script>  
  22. </body>  
  23. </html>
相關文章
相關標籤/搜索