什麼是 Geolocation API?
透過 Geolocation API 可以讓 Progressive Web App 存取用戶的位置,方便實作地理資訊相關應用。
怎麼使用 Geolocation API?
- 檢查支援度,然後針對支援的部分做漸進式增強,如果不支援的話可以使用 GEO IP 相關服務,雖然較不準確,但仍然有一定的參考價值。
https://get.geojs.io/v1/ip/geo.json
1 2 3 4 5
| if (navigator.geolocation) { console.log("Geolocation is supported!"); } else { console.log("Geolocation is not supported for this Browser/OS."); }
|
- 使用
navigator.geolocation.getCurrentPosition
一次性取得用戶地理位置資訊。
1 2 3 4 5 6 7 8 9 10 11
| var startPos; var geoSuccess = function (position) { startPos = position; console.log( "lat", startPos.coords.latitude, "lng", startPos.coords.longitude ); }; navigator.geolocation.getCurrentPosition(geoSuccess);
|
- 使用
navigator.geolocation.watchPosition
持續追蹤用戶地理位置資訊- enableHighAccuracy: 啟用後解析速度會下降,並且電池耗電會增加
- timeout: 避免讓用戶等太久,所以設置 timeout,超過就會跑錯誤處理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| var id, target, options;
function success(pos) { var crd = pos.coords;
if (target.latitude === crd.latitude && target.longitude === crd.longitude) { console.log("成功追蹤"); navigator.geolocation.clearWatch(id); } }
function error(err) { console.warn("ERROR(" + err.code + "): " + err.message); }
target = { latitude: 0, longitude: 0, };
options = { enableHighAccuracy: false, timeout: 5000, maximumAge: 0, };
id = navigator.geolocation.watchPosition(success, error, options);
|
- 不需要持續追蹤的時候,要記得使用
clearWatch
1
| navigator.geolocation.clearWatch(id);
|
請求權限
讓使用者同意位置共用的時機,在 App 啟動時就請求權限會是最爛的時機,而且對於在頁面載入時要求提供位置的網站,用戶通常會不信任。
在 Android 5.0 之後的實作上也是在要使用時才會向使用者請求權限,所以在實作上要假設:
- 假設使用者不會提供位置
- 說明為什麼需要存取使用者位置
在用戶使用特定功能時才讓用戶主動操作並出現提示,且要準備好使用被拒絕的備案。
圖片來源: https://developers.google.com/

喜歡這篇文章,請幫忙拍拍手喔 🤣