HTML5 內建的地理位置定位能力,讓前端也能做出 LBS 應用。這篇把整個 API 的使用要點整理成一份可查的筆記。
瀏覽器背後可能用到的定位方式有:IP 位址、GPS、Wi-Fi 基地台、GSM/CDMA 手機網路。前兩者最常見,而實際採用哪一種由瀏覽器與裝置自行決定,開發者無法指定,這也是為什麼同一份程式在不同裝置上精度會差很多。
整個流程中,使用者的同意是必要關卡——這是隱私設計的核心,任何繞過它的嘗試都不應該做。
Geolocation API 存在於 navigator 物件中,只包含三個方法:
getCurrentPosition:取得目前位置。watchPosition:持續監視位置變化。clearWatch:停止監視。支援的環境大致涵蓋 IE9+、Firefox 3.5+、Safari 5+、Chrome 5+、Opera 10.6+,以及 iOS 3+、Android 2+ 以後的行動裝置。實務上仍需以 if (navigator.geolocation) 做能力偵測,而不是假設它一定存在。
function isGeolocationAPIAvailable() {
var location = "No, Geolocation is not supported by this browser.";
if (window.navigator.geolocation) {
location = "Yes, Geolocation is supported by this browser.";
}
alert(location);
}
var nav = null;
function requestPosition() {
if (nav == null) {
nav = window.navigator;
}
if (nav != null) {
var geoloc = nav.geolocation;
if (geoloc != null) {
geoloc.getCurrentPosition(successCallback, errorCallback);
} else {
alert("Geolocation API is not supported in your browser");
}
} else {
alert("Navigator is not found");
}
}
function setLocation(val, e) {
document.getElementById(e).value = val;
}
function successCallback(position) {
setLocation(position.coords.latitude, "latitude");
setLocation(position.coords.longitude, "longitude");
}
除了 latitude 與 longitude,coords 上還有 accuracy(水平精度,單位公尺)、altitude、heading(行进方向)、speed 等欄位,多數桌面瀏覽器不會提供後三者。
watchPosition 和 clearWatch 的關係,有點像 setInterval 與 clearInterval:前者開始回報並取得一個 id,後者拿著這個 id 去取消。
function listenForPositionUpdates() {
if (nav == null) { nav = window.navigator; }
if (nav != null) {
var geoloc = nav.geolocation;
if (geoloc != null) {
watchID = geoloc.watchPosition(successCallback, errorCallback);
} else {
alert("Geolocation API is not supported in your browser");
}
} else {
alert("Navigator is not found");
}
}
function successCallback(position) {
setText(position.coords.latitude, "latitude");
setText(position.coords.longitude, "longitude");
}
// 不需要即時追蹤時取消
function clearWatch(watchID) {
window.navigator.geolocation.clearWatch(watchID);
}
提醒一下:watchPosition 會持續喚醒定位硬體,對電池消耗明顯,用完請記得 clearWatch,尤其是在行動裝置上。
第二個參數就是錯誤回呼,三種常見錯誤碼分別是 PERMISSION_DENIED(使用者拒絕)、POSITION_UNAVAILABLE(無法判定位置)、TIMEOUT(逾時)。
function errorCallback(error) {
var message = "";
switch (error.code) {
case error.PERMISSION_DENIED:
message = "This website does not have permission to use the Geolocation API";
break;
case error.POSITION_UNAVAILABLE:
message = "The current position could not be determined.";
break;
case error.TIMEOUT:
message = "The current position could not be determined within the specified timeout period.";
break;
}
if (message == "") {
message = "The position could not be determined due to an unknown error (Code: "
+ error.code.toString() + ").";
}
alert(message);
}
呼叫時也可以帶第三個參數來控制行為:{ enableHighAccuracy: true, timeout: 10000, maximumAge: 60000 }。enableHighAccuracy 會要求裝置盡可能使用 GPS,代價是更慢、更耗電;maximumAge 則允許瀏覽器回傳一定秒數內的快取值,能省下一次定位等待。
前提是 Google Maps 的 API 已經設定完成。這裡用 Static Maps 是最省事的作法:
function getCurrentLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showMyPosition, showError);
} else {
alert("No, Geolocation API is not supported by this browser.");
}
}
function showMyPosition(position) {
var coordinates = position.coords.latitude + "," + position.coords.longitude;
var map_url = "https://maps.googleapis.com/maps/api/staticmap?center="
+ coordinates + "&zoom=14&size=300x300";
document.getElementById("googlemap").innerHTML
= "<img src='" + map_url + "'>";
}
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
alert("This website does not have permission to use the Geolocation API");
break;
case error.POSITION_UNAVAILABLE:
alert("The current position could not be determined.");
break;
case error.TIMEOUT:
alert("The current position could not be determined within the specified timeout period.");
break;
case error.UNKNOWN_ERROR:
alert("The position could not be determined due to an unknown error.");
break;
}
}
兩個實務提醒:現在的 Static Maps 需要帶 API key,否則會被拒絕;另外,把座標直接串進 HTML 字串時,記得它仍來自外部輸入,組字串前應做基本的格式驗證。
近年來瀏覽器已全面收緊權限,Geolocation API 只在 HTTPS(或 localhost)環境下才會被允許呼叫,用 http 開啟的頁面會直接失敗。這是在本機開發時最常踩到的地雷之一。