DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML5詳解
HTML5 指南(4):用 Geolocation API 實作定位功能
編輯:HTML5詳解     

Geolocation 是 HTML5 裡最實用的原生能力之一。透過 navigator.geolocation 取得 Geolocation 物件後,手上有三個方法可用:

  • getCurrentPosition(callback, errorCallback, options):取得目前位置。
  • watchPosition(callback, errorCallback, options):開始持續監聽位置變化。
  • clearWatch(id):停止監聽。

以下範例使用 Chrome 測試,其他瀏覽器的輸出可能略有不同。

1. 取得目前位置

getCurrentPosition 不會同步回傳座標,而是透過 callback 函數把結果交給你——取得定位通常有延遲,而且瀏覽器一定會先跳出權限詢問視窗。

<!DOCTYPE Html>
<Html>
<head>
<title>Example</title>
<style>
table { border-collapse: collapse; }
th, td { padding: 4px; }
th { text-align: right; }
</style>
</head>
<body>
<table border="1">
<tr>
<th>Longitude:</th><td id="longitude">-</td>
<th>Latitude:</th><td id="latitude">-</td>
</tr>
<tr>
<th>Altitude:</th><td id="altitude">-</td>
<th>Accuracy:</th><td id="accuracy">-</td>
</tr>
<tr>
<th>Altitude Accuracy:</th><td id="altitudeAccuracy">-</td>
<th>Heading:</th><td id="heading">-</td>
</tr>
<tr>
<th>Speed:</th><td id="speed">-</td>
<th>Time Stamp:</th><td id="timestamp">-</td>
</tr>
</table>
<script>
navigator.geolocation.getCurrentPosition(displayPosition);

function displayPosition(pos) {
  var properties = ['longitude', 'latitude', 'altitude', 'accuracy',
                    'altitudeAccuracy', 'heading', 'speed'];
  for (var i = 0, len = properties.length; i < len; i++) {
    var value = pos.coords[properties[i]];
    document.getElementById(properties[i]).innerHTML = value;
  }
  document.getElementById('timestamp').innerHTML = pos.timestamp;
}
</script>
</body>
</Html>

回傳的 position 物件有兩個屬性:coords(座標資訊)與 timestamp(取得座標的時間)。coords 底下再分:

  • latitude:緯度
  • longitude:經度
  • altitude:高度
  • accuracy:水平精確度(公尺)
  • altitudeAccuracy:高度精確度(公尺)
  • heading:行进方向(0–360 度)
  • speed:行进速度(公尺/秒)

並不是每項都拿得到,這取決於裝置本身。有 GPS、加速度計與電子羅盤的手機能回傳大部分欄位;桌上型電腦則是依網際網路來源(IP 或 Wi-Fi)推估,通常只有經緯度與較大的 accuracy 誤差值,altitude、heading、speed 多半是 null。

按下「允許」後取得的結果:

還有一點務必注意:這個 API 只有在 HTTPS(或 localhost)下才會被允許使用。用 file:// 直接開頁面,多數瀏覽器會直接拒絕。

2. 錯誤處理

第二個參數就是錯誤回呼。傳入的 error 物件有兩個屬性:code 與 message,其中 code 有三種可能:

  • 1:使用者未授權使用定位。
  • 2:無法取得座標。
  • 3:逾時。
<!DOCTYPE Html>
<Html>
<head>
<title>Example</title>
<style>
table { border-collapse: collapse; }
th, td { padding: 4px; }
th { text-align: right; }
</style>
</head>
<body>
<table border="1">
<tr>
<th>Longitude:</th><td id="longitude">-</td>
<th>Latitude:</th><td id="latitude">-</td>
</tr>
<tr>
<th>Altitude:</th><td id="altitude">-</td>
<th>Accuracy:</th><td id="accuracy">-</td>
</tr>
<tr>
<th>Altitude Accuracy:</th><td id="altitudeAccuracy">-</td>
<th>Heading:</th><td id="heading">-</td>
</tr>
<tr>
<th>Speed:</th><td id="speed">-</td>
<th>Time Stamp:</th><td id="timestamp">-</td>
</tr>
<tr>
<th>Error Code:</th><td id="errcode">-</td>
<th>Error Message:</th><td id="errmessage">-</td>
</tr>
</table>
<script>
navigator.geolocation.getCurrentPosition(displayPosition, handleError);

function displayPosition(pos) {
  var properties = ["longitude", "latitude", "altitude", "accuracy",
                    "altitudeAccuracy", "heading", "speed"];
  for (var i = 0; i < properties.length; i++) {
    var value = pos.coords[properties[i]];
    document.getElementById(properties[i]).innerHTML = value;
  }
  document.getElementById("timestamp").innerHTML = pos.timestamp;
}

function handleError(err) {
  document.getElementById("errcode").innerHTML = err.code;
  document.getElementById("errmessage").innerHTML = err.message;
}
</script>
</body>
</Html>

選擇「拒絕」時的執行結果:

3. 使用 options 微調行為

第三個參數是可選的設定物件,共三個欄位:

  • enableHighAccuracy:是否要求最高精度(會改用 GPS,較耗電、較慢)。
  • timeout:逾時時間(毫秒)。
  • maximumAge:允許使用多久以內的快取值(毫秒)。
<script>
var options = {
  enableHighAccuracy: false,
  timeout: 2000,
  maximumAge: 30000
};
navigator.geolocation.getCurrentPosition(displayPosition, handleError, options);
</script>

實務上建議把 timeout 設得寬鬆一些(例如 8000–10000 毫秒)。設成 2000 毫秒在訊號不佳的室內很容易直接逾時,使用者會以為功能壞了。maximumAge 則是效能與即時性的取捨:設大一點可以減少定位次數、省電,代價是資料可能不夠新。

4. 持續監聽位置變化

watchPosition 的參數與 getCurrentPosition 完全相同,差別在於它會回傳一個 id,並在每次位置改變時重複呼叫 callback。想停止時,把 id 交給 clearWatch 即可。

<!DOCTYPE Html>
<Html>
<head>
<title>Example</title>
<style>
table { border-collapse: collapse; }
th, td { padding: 4px; }
th { text-align: right; }
</style>
</head>
<body>
<table border="1">
<tr>
<th>Longitude:</th><td id="longitude">-</td>
<th>Latitude:</th><td id="latitude">-</td>
</tr>
<tr>
<th>Altitude:</th><td id="altitude">-</td>
<th>Accuracy:</th><td id="accuracy">-</td>
</tr>
<tr>
<th>Altitude Accuracy:</th><td id="altitudeAccuracy">-</td>
<th>Heading:</th><td id="heading">-</td>
</tr>
<tr>
<th>Speed:</th><td id="speed">-</td>
<th>Time Stamp:</th><td id="timestamp">-</td>
</tr>
<tr>
<th>Error Code:</th><td id="errcode">-</td>
<th>Error Message:</th><td id="errmessage">-</td>
</tr>
</table>
<button id="pressme">Cancel Watch</button>
<script>
var options = {
  enableHighAccuracy: false,
  timeout: 2000,
  maximumAge: 30000
};

var watchID = navigator.geolocation.watchPosition(displayPosition, handleError, options);

document.getElementById("pressme").onclick = function (e) {
  navigator.geolocation.clearWatch(watchID);
};

function displayPosition(pos) {
  var properties = ["longitude", "latitude", "altitude", "accuracy",
                    "altitudeAccuracy", "heading", "speed"];
  for (var i = 0; i < properties.length; i++) {
    var value = pos.coords[properties[i]];
    document.getElementById(properties[i]).innerHTML = value;
  }
  document.getElementById("timestamp").innerHTML = pos.timestamp;
}

function handleError(err) {
  document.getElementById("errcode").innerHTML = err.code;
  document.getElementById("errmessage").innerHTML = err.message;
}
</script>
</body>
</Html>

按下 Cancel Watch 按鈕即停止監聽。

最後提醒:watchPosition 會持續喚醒定位硬體,忘記呼叫 clearWatch 是行動裝置耗電的常見兇手。如果頁面會被切到背景,記得在 visibilitychange 時把監聽停掉。範例原始檔名為 Html5Guide.Geolocation.zip。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved