Skip to main content

[JS30] Day21: Geolocation based Speedometer and Compass

這一天的挑戰目標是要透過瀏覽器內建的navigator知道使用者的地理位置資訊,並呈現移動速度、方向的資訊在畫面上。

JavaScript

Geolocation API也是只能在 https 的 secure server 使用 Geolocation.watchPosition()裡面可以放 1~3 個參數,如watchPosition(success, error, options),這裡帶入了 succes 函式和 error 函式。

watchPosition得到 data 之後,放入到speedarrow之中。

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);
}
);