
要在瀏覽器中取得使用者定位資訊,上網 GoogleWeb 定位關鍵字搜尋引擎馬上告訴你該使用哪支 API 了,navigator.geolocation只有三種 method 分別是:
getCurrentPosition():取得單次位置資訊navigator.geolocation.getCurrentPosition(
successCallback,
errorCallback,
options
);
watchPosition():開啟持續監聽,將返回一個 id 供clearWatch()使用clearWatch():刪除指定 id 的位置監聽const id = navigator.geolocation.watchPosition(
successCallback,
errorCallback,
options
);
navigator.geolocation.clearWatch(id);
navigator.geolocation.watchPosition(
(data) => {
console.log(data);
},
(err) => {
console.error(err);
}
);
每次印出的資料會包含一個coordsGeolocationCoordinates 座標物件以及一個timestamp時間戳記,我們所有的資料都存放在coords中,每個屬性如下:

但你會發現用瀏覽器印出來我們這題需要的方向及速度還有一些參數,都是 null,也不可能要你開發的時候帶著手機電腦在路上邊移動邊寫程式,因此作者幫我們找到了模擬定位的方法,那就是蘋果系統的開發工具Xcode,安裝好之後打開點選視窗右上角Xcode>Open Developer Tool>打開手機模擬器Simulator然後你就打開了一個手機模擬器。

browser-sync套件,執行npm run start指令後部署網頁於本機 IP 3000 port,再將 External 複製到手機模擬器中的 Safari 瀏覽器開啟。<h1>下方新增了此結構,每次取得資訊都即時全部顯示於畫面上<ul class="dataContainer">
<li class="accuracy"></li>
<li class="altitude"></li>
<li class="altitudeAccuracy"></li>
<li class="heading"></li>
<li class="latitude"></li>
<li class="longitude"></li>
<li class="speed"></li>
<li class="floorLevel"></li>
</ul>
.dataContainer {
font-size: 20px;
color: white;
}
ul {
padding: 0;
list-style: none;
}
navigator.geolocation.watchPosition(
(data) => {
console.log(data);
// 計算時速並取到小數點後第二位,
// 因為速度單位為(公尺/秒)所以x3600秒/1000公尺= KM公里/H小時
speed.textContent = (data.coords.speed * 3.6).toFixed(2);
// 羅盤依方位數值設定旋轉角度
arrow.style.transform = `rotate(${data.coords.heading}deg)`;
// 將位置屬性渲染至對應名稱的節點textContent中
for (const key in data.coords) {
document.querySelector(
`.${key}`
).textContent = `${key}:${data.coords[key]}`;
}
},
(err) => {
console.error(err);
}
);