iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 22
0
Modern Web

寫JS30天系列 第 22

JS30 - 22 - Geolocation

今天這個geolocation API可以拿到使用者的位置
但需要取得使用者的授權
使用nevigator.geolocation這個物件,可以取得裝置的地理相關資訊

不過在做這些之前
需要先假設local server
可以使用JS30給的package.json
也可以用Xcode
我自己是用pthon來架設local server

getCurrentPosition()是可以拿到即時的位置訊息
watchPosition()是可以持續追蹤位置,一但位置有變,會更新內容

navigator.geolocation.watchPosition(data => {
    console.log(data)
});

東西都藏在coords內!

coords.latitude緯度
coords.longitude經度
coords.altitude高度
coords.heading和北邊(0度)的順時針角度
coords.speed速度

取得這些資訊就可以拿來做一些定位相關的服務。

<h1 class="speed">
    <span class="speed-value">0</span>
    <span class="units">KM/H</span>
</h1>
<div class="latitude"></div>
<div class="longitude"></div>
navigator.geolocation.watchPosition(data=> {
    speed.textContent = data.coords.speed;
    arrow.style.transform = "rotate(`${data.coords.heading}`deg)";
    latitude.textContent = `緯度:${data.coords.latitude}`;
    longitude.textContent = `經度:${data.coords.longitude}`;
})

上一篇
JS30 - 21 - Native Speech Recognition
下一篇
JS 30 - 23 - Follow Along Link Highlighter
系列文
寫JS30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言