H5系列之地理位置(必知必會)


H5之地理位置必知必會
 
 
【02】概念
 
 
 
HTML5 Geolocation(地理定位)用於定位用戶的位置。
定位用戶的位置HTML5 Geolocation API 用於獲得用戶的地理位置。鑒於該特性可能侵犯用戶的隱私,除非用戶同意,否則用戶位置信息是不可用的。
 

HTML5 Geolocation API 允許我們對喜歡的網站共享我們的位置。JavaScript 可以捕獲到緯度和經度,還可以發送給后端服務器,然后做一些位置感知的事情,比如查找本地企業或者在地圖上顯示我們的位置。

 

 
【】嚴格來說,Geolocation API並不屬於HTML5標准規范,但其API接口使得它能讓瀏覽器或者移動設備的瀏覽器獲取用戶的當前位置信息。
由於地理定位涉及用戶個人隱私信息,因此在任何時候第一次使用Geolocation地理定位功能的頁面,都需要用戶確認是否允許Web應用程序獲取自己的位置信息。
 
圖7-1顯示了在iPhone的Safari瀏覽器下,用戶第一次使用地理定位功能時,默認提示用戶是否接受瀏覽器的獲取地理位置信息。
總的來說,在PC的瀏覽器中 HTML5 的地理位 置功能獲取的位置精度不夠高,如果借助這個 HTML5 特性做一個城市天氣預報是綽綽有余,但如果是做一個地圖應用,那誤差還是太大了。
不過,如果是移動設備上的 HTML5 應用,可以通 過設置  enableHighAcuracy 參數為 true, 調用設備的 GPS 定位來獲取高精度的地理位置信息。
 
Geolocation API(地理位置API)
 
 
用途:
 
 
1. Geolocation API的應用
Geolocation API能夠將用戶所在地理位置信息發送給用戶許可的站點,而站點可以利用這些 信息為用戶提供位置相關的服務,例如顯示用戶位置、尋找周邊商家、導航行車路線等。
 
2. 地理位置的獲取方式
獲取地理位置的方式有很多種,雖然因獲取方式的工作原理不同,它們有非常明顯的精度差 異,但是在實際工作環境中,又有各自的優點和不足。
 
 IP地址
這是一種比較不准確地獲取地理位置的辦法,很多時候獲取的是ISP機房的位置,但是獲取 非常方便,沒有什么限制。大多數時候,IP地址還是比較准確的,基本上能精確到某個小區或某 個大樓,但是如果用戶使用代理或者VPN,就可能導致非常大的偏差。
 
 GPS
這是一種非常准確地獲取地理位置的方法, GPS的精度可以達到10米左右。如果用來找人或 者找建築,基本上都在目視范圍內。但是使用GPS還有一些限制:在室內使用時,信號不太穩定, 搜索衛星的時間較長,會造成延時。使用GPS最大的障礙是:很多設備(比如筆記本電腦)基本 上都不帶GPS,而只有智能手機才有。
 
 Wi-Fi基站
連接位置已知的公共Wi-Fi時,可以獲得地理位置信息。這種定位的精度比較不錯,而且還 可以在室內定位。不過由於位置公開的Wi-Fi比較少,此種方法的適用范圍比較少。從目前的各 類科技新聞來看,北京、上海、廣州將率先建立公共Wi-Fi基站,北京甚至在公交車上都已經設 立Wi-Fi基站,這些也可以考慮到未來的應用中。
 
 GSM或CDMA基站
通過電話局基站定位,定位精度隨基站密度變化,精度非常一般,而且只有手機才能使用, 並且地理位置信息往往不太精確。
綜上所述,Geolocation API在移動設備上比較實用,而在個人電腦上常用於電子地圖查詢。
 
 
3. 地理位置獲取流程
由於地理位置信息涉及個人隱私,是受到法律保護的,因此,每當用戶在使用地理位置信息 時,提供地理位置獲取服務的軟件都應該遵守地理位置獲取的技術流程,經由用戶同意,才可以 獲取信息。在桌面瀏覽器上,此技術流程大致如下(在移動設備非瀏覽器環境下會略有差異):
 
(1) 用戶打開需要獲取地理位置的Web應用;
(2) 應用向瀏覽器請求地理位置,瀏覽器彈出詢問窗口,詢問用戶是否共享地理位置;
(3) 假設用戶允許,瀏覽器從設備查詢相關信息;
(4)  瀏覽器將相關信息發送到一個信任的位置服務器,服務器返回具體的地理位置。
 
 

【02】語法
 
 
 

地理定位 APIs 是作為全局 navigator 對象的一個新屬性工作的。可以按照如下方式創建地理定位對象:

var geolocation = navigator.geolocation;

地理對象是一個允許組件檢索設備地理位置相關信息的服務對象。

 
 
此屬性指代一個擁有如下這三個方法的對象:
 
navigator.geolocation.getCurrentPosition()
 
 
獲取用戶當前位置。
 
navigator.geolocation.watchPosition()
 
 
獲取當前位置,同時不斷地監視當前位置,一旦用戶位置發生更改,就會調用指定的回調函數。
 
navigator.geolocation.clearWatch()
 
停止監視用戶位置。傳遞給此方法的參數應當是調用watchPosition()方法獲得的返回值。
 

 
如下代碼展示了一個獲取位置的簡單例子:
 
navigator.geolocation.getCurrentPosition(function(pos) {
        var latitude = pos.coords.latitude;
        var longitude = pos.coords.longitude;
        alert("Your position: " + latitude + ", " + longitude);
});
 
除了經度和緯度外,凡是成功獲取到的地理位置信息還包括一個精度值(米為單位),該值表示獲取到的位置信息精度是多少。
 
 
 

 
【00】geolocation兼容性
 
 
 
 
 **
 
 
瀏覽器支持

Internet Explorer 9、Firefox、Chrome、Safari 以及 Opera 支持地理定位。注釋:對於擁有 GPS 的設備,比如 iPhone,地理定位更加精確。
 
 
 
【05】檢測瀏覽器是否支持Geolocation API
檢測瀏覽器是否支持Geolocation API
Geolocation API在瀏覽器上的能力檢測代碼如下:
 
 
if(navigator.geolocation){
//你的瀏覽器支持Geolocation API
} else{
//你的瀏覽器不支持Geolocation API
}
 
 
【】如何使用Geolocation API
Geolocation API是通過window.navigator.geolocation獲得對地理定位的訪問的。
該對象有如下三個方法:
 
方法 描述
getCurrentPosition()

這個方法用於檢索用戶的當前地理位置。

watchPosition()

這個方法用於檢索設備當前地理位置定期更新信息。

clearWatch()

這個方法用於取消 watchPosition 方法調用。

示例

下面是一個使用上述方法的示例代碼:

functiongetLocation(){
   var geolocation = navigator.geolocation;
   geolocation.getCurrentPosition(showLocation, errorHandler);
}

這里的 showLocation 和 errorHandler 分別是用來獲取實際位置和處理錯誤的回調方法。

 

監視移動設備的位置變化
watchPosition和clearWatch是一對方法,其原理和setInterval、setTimeout方法相同。watchPosition方法會返回一個唯一標識,clearWatch可通過這個唯一標識清除watchPosition方法的監聽。
watchPosition的語法和getCurrentPosition相同,可以傳入三個參數,分別是
● 第一個參數是監聽成功后返回的函數;(必選)
● 第二個參數是監聽失敗時返回的函數;(可選) 該函數會傳遞一個參數到函數內部,該參數記錄着返回的錯誤信息。
● 第三個參數 (可選) 指定了是否需要高精度的位置信息,該位置信息的過期時間,以及允許系統在多長時間內獲取位置信息。
 
 
【】 watchPosition() 
 - 返回用戶的當前位置,並繼續返回用戶移動時的更新位置(就像汽車上的 GPS)。
使用watchPosition()時,可以持續獲取地理位置信息,瀏覽器多次調用updateLocation() 函數以便傳遞最新的位置。該函數返回一個watchID,使用navigator.geolocation. clearWatch(watchId)可以清除此updateLocation()函數的回調,使用不帶參數的navigator。
 
 
【】 geolocation.clearWatch()
- 停止 watchPosition() 方法。
可以清除watchPosition()方法信息。

下面的例子展示 watchPosition() 方法。您需要一台精確的 GPS 設備來測試該例(比如 iPhone):

實例

<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>
 
示例
<!DOCTYPE html>
<html lang="zh-cn">

<head>
	<meta charset="utf-8">
	<title>moyu's demo</title>
</head>
<body>

<script type="text/javascript"> navigator.geolocation.getCurrentPosition(function(pos){ console.log("當前地理位置的緯度: "+pos.coords.latitude); console.log("當前地理位置的經度: "+pos.coords.longitude); console.log("當前地理位置的精度: "+pos.coords.accuracy); }); var watchID = navigator.geolocation.watchPosition(function(pos){ console.log("當前位置變化的緯度: "+pos.coords.latitude); console.log("當前位置變化的經度: "+pos.coords.longitude); console.log("當前位置變化的精度: "+pos.coords.accuracy); navigator.geolocation.clearWatch(watchID); },function(){}); </script>
</body>

</html>
 
 
 
 
 

**


【02】getCurrentPosition()
 
 

Description

The getCurrentPosition method retrieves the current geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed. The location information is returned in a Position object.

Syntax

Here is the syntax of this method −

getCurrentPosition(showLocation, ErrorHandler, options);

Parameters

Here is the detail of parameters −

  • showLocation − This specifies the callback method that retrieves the location information. This method is called asynchronously with an object corresponding to the Position object which stores the returned location information.

  • ErrorHandler − This optional parameter specifies the callback method that is invoked when an error occurs in processing the asynchronous call. This method is called with the PositionError object that stores the returned error information.

  • options − This optional parameter specifies a set of options for retrieving the location information. You can specify (a) Accuracy of the returned location information (b) Timeout for retrieving the location information and (c) Use of cached location information.

Return value

The getCurrentPosition method does not return a value.

 
<!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>
 
 
 

**


【03】watchPosition() 
 
 
 
 
 

如果你希望跟蹤用戶的位置,那么可以使用另一個方法watchPosition()。這個方法接收的參數與getCurrentPosition()方法完全相同。實際上,watchPosition()與定時調用getCurrentPosition()的效果相同。在第一次調用watchPosition()方法后,會取得當前位置,執行成功回調或者錯誤回調。

 

然后,watchPosition()就地等待系統發出位置已改變的信號(它不會自己輪詢位置)。

調用watchPosition()會返回一個數值標識符,用於跟蹤監控的操作。基於這個返回值可以取消監控操作,只要將其傳遞給clearWatch()方法即可(與使用setTimeout()clearTimeout()類似)。

 

例如:

var watchId = navigator.geolocation.watchPosition(function(position){
    drawMapCenteredAt(position.coords.latitude, positions.coords.longitude);
}, function(error){
    console.log("Error code: " + error.code);
    console.log("Error message: " + error.message);
});

clearWatch(watchId);
 

以上例子調用了watchPosition()方法,將返回的標識符保存在了watchId中。然后,又將watchId傳給了clearWatch(),取消了監控操作。

 

 
 
 

Description

The watchPosition method retrieves periodic updates about the current geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed.

The location information is returned in a Position object. Each update returns a new Position object.

Syntax

Here is the syntax of this method −

watchPosition(showLocation, ErrorHandler, options);

Parameters

Here is the detail of parameters −

  • showLocation − This specifies the callback method that retrieves the location information. This method is called asynchronously with an object corresponding to the Position object which stores the returned location information.

  • ErrorHandler − This optional paramter specifies the callback method that is invoked when an error occurs in processing the asynchronous call. This method is called with the PositionError object that stores the returned error information.

  • options − This optional paramter specifies a set of options for retrieving the location information. You can specify (a) Accuracy of the returned location information (b) Timeout for retrieving the location information and (c) Use of cached location information .

Return value

The watchPosition method returns a unique transaction ID (number) associated with the asynchronous call. Use this ID to cancel the watchPosition call and to stop receiving location updates.

Example

<!DOCTYPE HTML><head><html><scripttype="text/javascript">var watchID;var geoLoc;functionshowLocation(position){var latitude = position.coords.latitude;var longitude = position.coords.longitude;
            alert("Latitude : "+ latitude +" Longitude: "+ longitude);}functionerrorHandler(err){if(err.code ==1){
               alert("Error: Access is denied!");}elseif( err.code ==2){
               alert("Error: Position is unavailable!");}}functiongetLocationUpdate(){if(navigator.geolocation){// timeout at 60000 milliseconds (60 seconds)var options ={timeout:60000};
               geoLoc = navigator.geolocation;
               watchID = geoLoc.watchPosition(showLocation, errorHandler, options);}else{
               alert("Sorry, browser does not support geolocation!");}}</script></head><body><form><inputtype="button"onclick="getLocationUpdate();"value="Watch Update"/></form></body></html>
 

**


【04】clearWatch()
 

Description

The clearWatch method cancels an ongoing watchPosition call. When cancelled, the watchPosition call stops retrieving updates about the current geographic location of the device.

Syntax

Here is the syntax of this method −

clearWatch(watchId);

Parameters

Here is the detail of parameters −

  • watchId − This specifies the unique ID of the watchPosition call to cancel. The ID is returned by the watchPosition call.

Return value

The clearWatch method does not return a value.

Example

<!DOCTYPE HTML><html><head><scripttype="text/javascript">var watchID;var geoLoc;functionshowLocation(position){var latitude = position.coords.latitude;var longitude = position.coords.longitude;
            alert("Latitude : "+ latitude +" Longitude: "+ longitude);}functionerrorHandler(err){if(err.code ==1){
               alert("Error: Access is denied!");}elseif( err.code ==2){
               alert("Error: Position is unavailable!");}}functiongetLocationUpdate(){if(navigator.geolocation){// timeout at 60000 milliseconds (60 seconds)var options ={timeout:60000};
               geoLoc = navigator.geolocation;
               watchID = geoLoc.watchPosition(showLocation, errorHandler, options);}else{
               alert("Sorry, browser does not support geolocation!");}}functionstopWatch(){
            geoLoc.clearWatch(watchID);}</script></head><body><form><inputtype="button"onclick="getLocationUpdate();"value="Watch Update"/><inputtype="button"onclick="stopWatch();"value="Stop Watch"/></form></body></html>
 
 

**


【05】 返回的位置對象的屬性
 
 

返回的位置對象的屬性

地理定位方法 getCurrentPosition() 和 getPositionUsingMethodName() 指定了檢索位置信息的回調方法。

這些方法使用一個存儲完整位置信息的 Position 對象異步調用。

 

這個 Position 對象指定了設備的當前地理位置。這個位置以一組帶有方向和速度信息的地理坐標表示。

下面的表格描述了 Position 對象的屬性。對於可選屬性,如果系統沒有提供值,則該屬性值為 null。

屬性 類型 描述
coords objects

表示設備的地理位置。位置以一組帶有方向和速度信息的地理坐標表示。

coords.latitude Number

十進制的緯度估值。值范圍為 [-90.00, +90.00]。

coords.longitude Number

十進制的經度固執。值范圍為 [-180.00, +180.00]。

coords.altitude Number

【可選】 WGS-84 球面以上的海拔高度固執,以米為單位計算。

如果沒有相關數據則值為null
coords.accuracy Number

【可選】 以米為單位的緯度和經度精確估值。

coords.altitudeAccuracy Number

【可選】 以米為單位的海拔高度精確估值。

數值越大越不精確。
coords.heading Number

【可選】 相對正北方向設備以順時針方向運動計算的當前方向。

指南針的方向,0°表示正北,值為NaN表示沒有檢測到數據。
coords.speed Number

【可選】 以米/每秒為單位的設備當前地面速度。

即每秒移動多少米,如果沒有相關數據則值為null

timestamp date

檢索位置信息和創建 Position 對象的日期時間。

處理錯誤

地理定位是復雜的。非常需要我們捕獲任意錯誤並處理它。

地理定位方法 getCurrentPosition() 和 watchPosition() 可以使用一個提供 PositionError 對象的錯誤處理回調方法。

這個對象有下列兩屬性。

屬性 類型 描述
code Number

錯誤碼。

message String

錯誤描述信息。

下面這個表格描述了 PositionError 對象可能返回的錯誤碼。

錯誤碼 常量 描述
0 UNKNOWN_ERROR

由於未知錯誤,檢索設備位置信息失敗。

1 PERMISSION_DENIED

由於應用程序沒有權限使用位置服務,檢索設備位置信息失敗。

用戶拒絕了定位服務的請求。

2 POSITION_UNAVAILABLE

設備位置信息無法確定。沒有獲取正確的地理位置信息。

位置無效。
3 TIMEOUT

不能在給定的最大超時區間內檢索位置信息。

獲取位置的操作超時。

在error對象中,除"code"屬性表示出錯數字外,還可以通過"message"屬性獲取出錯的詳細文字信息。該屬性是一個字符串,包含與"code"屬性值相對應的錯誤說明信息。

實例

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;
    }
  }
 
 
 
 

**


【06】
options選項

下面是 getCurrentPosition() 方法的實際語法:

getCurrentPosition(callback, ErrorCallback, options)

其中第三個參數是指定一組檢索設備地理位置選項的 PositionOptions 對象。

下列選項可以指定為第三個參數:

屬性 類型 描述
enableHighAccuracy Boolean

布爾值,是否想要檢索最精准的位置估值默認值為 false。

屬性是指定瀏覽器或移動設備嘗試更精確地讀取經度和緯度,默認值為false。當這個屬性參數設置為true時,移動設備在定位計算上可能會花費更長時間,也容易導致消耗更多的移動設備電量。因此,如果無較高准確定位的需求,應該將參數設置為false或不設置。
timeout Number

timeout 屬性就是 Web 應用程序要等待定位的毫秒數。
設置獲取地理位置的超時限制(單位:毫秒)。超過時觸發errorCallback回調函數,error.code的屬性值為3,表示已超時。

默認不限時。
maximumAge Number

用於緩存位置信息的過期時間毫秒數。
設置緩存獲取的地理位置數據信息的有效時間(單位:毫秒),超過設置的時間時重新獲取,否則調用緩存中的數據信息。

最長有效期,在重復獲取地理位置時,此參數指定多久再次獲取位置。
默認為0,表示瀏覽器需要立刻重新計算位置。
 

如:

navigator.geolocation.getCurrentPosition(function(position){
    drawMapCenteredAt(position.coords.latitude, positions.coords.longitude);
}, function(error){
    console.log("Error code: " + error.code);
    console.log("Error message: " + error.message);
}, {
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 25000
});
 

這三個選項都是可選的,可以單獨設置,也可以與其他選項一起設置。

 

除非確實需要非常精確的信息,否則建議保持enableHighAccuracyfalse值(默認值)。將這個選項設置為true需要更長的時候,而且在移動設備上還會導致消耗更多電量。類似地,如果不需要頻繁更新用戶的位置信息,那么可以將maximumAge設置為Infinity,從而始終都使用上一次的坐標信息。

 

 
 
例子:
navigator.geolocation.getCurrentPosition(function(pos){
	console.log("當前地理位置的緯度: "+pos.coords.latitude);
	console.log("當前地理位置的經度: "+pos.coords.longitude);
	console.log("當前地理位置的精度: "+pos.coords.accuracy);

},function(err){
	if (err.code == 1) {
		// access is denied
	}
}, {maximumAge: 75000});
 

【】魔芋測試:(在瀏覽器中無效。)

IMG_0141.PNG

 

 

IMG_0142.PNG

 
 

火狐截圖:

 
 
 
 
 
 
 
 

**

 

 
 
 

 

 
 
 
 

**


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM