JS30-21-Geolocation

取得裝置的地理位置和速度

目標

  • 取得裝置的地理位置和速度。

實踐步驟

  1. 利用 navigator.geolocation 取得裝置的地理位置和速度

成品

[DEMO] | [GitHub]


JS學習紀錄

紀錄JS如何取得裝置的地理位置和速度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 取得DOM元素
const arrow = document.querySelector('.arrow');
const speed = document.querySelector('.speed-value');

// 取得裝置的地理位置和速度
navigator.geolocation.watchPosition((data) => {
// 若有成功取得,則會回傳一組 Position
console.log(data);

// data.coords.speed 取得 速度(公尺/秒)
speed.textContent = data.coords.speed;

// data.coords.heading 取得 角度(0為正北、90為正東)
arrow.style.transform = `rotate(${data.coords.heading}deg)`;
}, (err) => {
console.error(err);
});