想知道使用者現在在哪裡?HTML5 的 Geolocation API 只要幾行程式就能拿到經緯度。本文示範完整流程,並附上實測各家瀏覽器的相容性與反應速度比較。
核心是 navigator.geolocation.getCurrentPosition(),第一個參數是成功回呼,第二、第三個參數分別是錯誤回呼與選項設定。呼叫前務必做特性偵測,因為不支援的環境下 navigator.geolocation 會是 undefined。
<!DOCTYPE Html>
<Html>
<head>
<title>取得我的座標</title>
<meta http-equiv="content-type" content="text/Html; charset=UTF-8">
</head>
<body>
<div id="demo">點擊下面的按鈕,取得您的座標:</div>
<button onclick="getLocation()">試一下</button>
<script type="text/Javascript">
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "這個瀏覽器不支援地理定位!";
}
}
function showPosition(position) {
x.innerHTML = "緯度 Latitude: " + position.coords.latitude +
"<br/>經度 Longitude: " + position.coords.longitude;
}
function showError(error) {
var msg = {
1: "使用者拒絕了定位請求",
2: "無法取得位置資訊",
3: "定位逾時"
};
x.innerHTML = "定位失敗:" + msg[error.code];
}
</script>
</body>
</Html>
position.coords 除了 latitude 與 longitude,通常還附帶 accuracy(以公尺為單位的半徑誤差範圍)、altitude、altitudeAccuracy、heading(行进方向)與 speed。其中只有前兩項與 accuracy 是普遍可用的,其餘在不少裝置上會是 null。
在 IE9、Firefox、Chrome、Opera 上都能成功取得座標;Safari 5.x 則遲遲沒有回應,這個現象在當時頗令人費解。就反應速度而言,Chrome 最快,Opera 次之,接著是 IE9,Firefox 反而最慢。
值得補充的是,這個差異並不代表瀏覽器本身的執行效能,而是取決於背後的定位來源:桌機多靠 Wi-Fi 基地台與 IP 位址比對,速度與資料庫完整度有關;行動裝置則會優先使用 GPS 晶片,冷啟動時間可能長達數十秒。
watchPosition(),它會回傳一個 id,不再需要時呼叫 clearWatch(id) 取消即可。另外提醒,經緯度屬於個人敏感資訊,取得前應明確告知使用者用途,並在使用後立即拋棄,不要默默存進資料庫。