close

html5.jpg

定位用戶的位置

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

鑑於該特性可能侵犯用戶的隱私,除非用戶同意,否則用戶位置信息是不可用的。


瀏覽器支持

Internet Explorer 9、Firefox、Chrome、Safari 以及Opera 支持地理定位。

註釋:對於擁有GPS的設備,比如iPhone,地理定位更加精確。


HTML5 - 使用地理定位

請使用getCurrentPosition() 方法來獲得用戶的位置。

下例是一個簡單的地理定位實例,可返回用戶位置的經度和緯度。

實例

<script>
var x=document.getElementById("demo");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation. <code>getCurrentPosition(showPosition)</code> ;
    }
  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>
	

例子解釋:

  • 檢測是否支持地理定位
  • 如果支持,則運行getCurrentPosition() 方法。如果不支持,則向用戶顯示一段消息。
  • 如果getCurrentPosition()運行成功,則向參數showPosition中規定的函數返回一個coordinates對象
  • showPosition() 函數獲得併顯示經度和緯度

上面的例子是一個非常基礎的地理定位腳本,不含錯誤處理。


處理錯誤和拒絕

getCurrentPosition() 方法的第二個參數用於處理錯誤。它規定當獲取用戶位置失敗時運行的函數:

實例

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

錯誤代碼:

  • Permission denied - 用戶不允許地理定位
  • Position unavailable - 無法獲取當前位置
  • Timeout - 操作超時

在地圖中顯示結果

如需在地圖中顯示結果,您需要訪問可使用經緯度的地圖服務,比如google map:

實例

function showPosition(position)
{
var latlon=position.coords.latitude+","+position.coords.longitude;
var img_url="http://maps.googleapis.com/maps/api/staticmap?center="
+latlon+"&zoom=14&size=400x300&sensor=false";
document.getElementById("mapholder").innerHTML="<img src='"+img_url+"' />";
}
	

給定位置的信息

本頁演示的是如何在地圖上顯示用戶的位置。不過,地理定位對於給定位置的信息同樣很有用處。

案例:

  • 更新本地信息
  • 顯示用戶周圍的興趣點
  • 交互式車載導航系統(GPS)

getCurrentPosition() 方法- 返回數據

若成功,則getCurrentPosition() 方法返回對象。始終會返回latitude、longitude 以及accuracy 屬性。如果可用,則會返回其他下面的屬性。

屬性 描述
coords.latitude 十進制數的緯度
coords.longitude 十進制數的經度
coords.accuracy 位置精度
coords.altitude 海拔,海平面以上以米計
coords.altitudeAccuracy 位置的海拔精度
coords.heading 方向,從正北開始以度計
coords.speed 速度,以米/每秒計
timestamp 響應的日期/時間

Geolocation 對象- 其他有趣的方法

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

clearWatch() - 停止watchPosition() 方法

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

實例

<script>
var x=document.getElementById("demo");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation. <code>watchPosition(showPosition)</code> ;
    }
  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>
	
arrow
arrow

    設計密碼工作室 發表在 痞客邦 留言(0) 人氣()