目標
用navigator.geolocation
API 取得地理位置、速率
step 1 : 取得 HTML 中的元素
- 取得 arrow、speed 的 class selector
const arrow = document.querySelector('.arrow');
const speed = document.querySelector('.speed-value');
- 拿到當前的地理位置
getPosition()
=> 一次性取得當前的地理位置
watchPostion()
=> 及時監控當前地理位置
navigator.geolocation.watchPosition((data) => {
conosle.log(data)
}
- 拿到相關參數
coords.accurency
:目前位置的精確度
coords.heading
:目前位置指向的角度,表示偏離北方的角度,0為正北、90為正東...以此類推
coords.latitude
:目前位置經度
coords.longitude
:目前位置緯度
coords.speed
:當前速度(公尺/秒)。
step 2 : 將資料帶入 arrow、speed 區塊
const arrow = document.querySelector('.arrow');
const speed = document.querySelector('.speed-value');
navigator.geolocation.watchPosition((data) => {
conosle.log(data)
speed.textContent = data.coords.speed;
arrow.style.transform = `rotate(${data.coords.heading}deg)`;
}
step 3 : navigator.geolocation 的第二個參數為錯誤處理
const arrow = document.querySelector('.arrow');
const speed = document.querySelector('.speed-value');
navigator.geolocation.watchPosition((data) => {
console.log(data);
speed.textContent = data.coords.speed;
arrow.style.transform = `rotate(${data.coords.heading}deg)`;
}, (err) => {
console.error(err);
});
參考資料: