# JS30 Day21
### Geolocation based Speedometer and Compass
###### tags: `JS 30`
by Angelina
---
geolocation 地理定位
---
compass 指南針
---
Speedometer 時速
---
1. 建置環境
---
為取得正確資料以便使用
建議使用 ios 模擬器
---
若沒有 mac
可使用模器裝置來模擬手機設備
或在手機上使用
---
有 mac
可以下載 xcode
[xcode載點](https://developer.apple.com/download/)
---
安裝後介面

---
開啟模擬器
Developer Tool -> Simulator

---
模擬器介面

---
其他模擬器選擇
hardware -> Devices

---
備註
此項目要取得安全同源(secure origin)
要用https的方式或是localhost
步驟裡有一些需要打開的權限,記得打開
---
將資料夾抓下來後
輸入指令
npm install
npm start

---
Local 貼到瀏覽器
ip 貼到模擬器上

---

---

---
開啟模擬器 dev tool
safari -> develop -> simulator -> ip - index.START.html

---
環境建置完成!
---
2. 程式碼
---
取得指南針指向位置、當前時速
```javascript=
const arrow = document.querySelector('.arrow');
const speed = document.querySelector('.speed-value');
```
---
取得當前的地理位置
Navigator.geolocation
1. getPosition() 以一次性地取得當前的地理位置
2. watchPosition() 以監控的方式連續取得當前地理位置
---
使用 watchPosition() 追蹤目前位置
```javascript=
const arrow = document.querySelector('.arrow');
const speed = document.querySelector('.speed-value');
navigator.geolocation.watchPosition((data) => {
conosle.log(data)
}
```
---
accurency 目前位置的精確度
->heading 目前位置指向
latitude, longitude 經度、緯度
->speed 當前速度

---
放上指南針指向位置、當前時速
```javascript=
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)`;
}
```
---
處理錯誤
```javascript=
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);
});
```
---

---
參考資料
* [Geolocation](https://github.com/dustinhsiao21/Javascript30-dustin/tree/master/21%20-%20Geolocation)
* [JS30-Day21-Geolocation](https://ithelp.ithome.com.tw/articles/10196561)
* [課程影片連結](https://courses.wesbos.com/account/access/60d9d14e8981fd4f94701bb5/view/194128542)
---
{%youtube bnagAr8EsM8 %}
{"metaMigratedAt":"2023-06-16T05:15:26.741Z","metaMigratedFrom":"Content","title":"JS30 Day21","breaks":true,"contributors":"[{\"id\":\"e66977c1-c757-4957-8123-cd26044bbbba\",\"add\":2994,\"del\":378}]"}