Skip to content

Commit b620a4f

Browse files
committed
add readMe file to challenge 21
1 parent edaa48d commit b620a4f

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

21 - Geolocation/README.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
---
2+
title: javascript30-day21 - Geolocation
3+
layout: post
4+
cdn: header-on
5+
date: 2017-07-07 21:38:19
6+
tags:
7+
- Javascript
8+
---
9+
10+
> 在Github上看到了[wesbos](https://twitter.com/wesbos)的一个Javascript30天挑战的[repo](https://github.com/wesbos/JavaScript30),旨在使用纯Js来进行练习,不允许使用任何其他的库和框架,该挑战共30天,我会在这里记录下自己练习的过程和遇到的问题。
11+
12+
## day21 - Geolocation
13+
14+
第21天的目的是练习`NavigatorGeolocation.geolocation`这一webAPI的使用,通过使用此API可以访问到设备的位置信息。这允许网站或应用根据用户的位置提供个性化结果。
15+
16+
[线上例子](http://htmlpreview.github.io/?https://github.com/winar-jin/JavaScript30-Challenge/blob/master/21%20-%20Geolocation/index.html)
17+
**建议打开电脑上移动端的模拟器或者直接用手机体验位置信息**
18+
**该功能仅仅在https模式下才可正常使用**
19+
20+
![Demo](/images/0707-location.png)
21+
22+
## 主要代码
23+
```Javascript
24+
const arrow = document.querySelector('.arrow');
25+
const speed = document.querySelector('.speed-value');
26+
27+
navigator.geolocation.watchPosition((data) => {
28+
console.log(data);
29+
speed.textContent = data.coords.speed;
30+
arrow.style.transform = `rotate(${data.coords.heading}deg)`;
31+
}, (err) => {
32+
console.error(err);
33+
});
34+
```
35+
可以看到只要通过调用`navigator.geolocation``watchPosition`方法就可以获取到位置的信息。
36+
37+
在此获取到的信息为`data`,以回调函数的形式返回,当获取到位置信息之后,在动态的修改页面中`speed`显示的内容和指南针旋转的角度。
38+
39+
40+
## `Navigator` API的使用与说明
41+
42+
> Geolocation.watchPosition() 用于注册监听器,在设备的地理位置发生改变的时候自动被调用。也可以选择特定的错误处理函数。
43+
44+
> 该方法会返回一个 ID,如要取消监听可以通过 Geolocation.clearWatch() 传入该 ID 实现取消的目的。
45+
46+
> --- [Geolocation API in MDN](https://developer.mozilla.org/zh-CN/docs/Web/API/Geolocation/watchPosition)
47+
48+
除了`watchPosition()`方法,还有一个`getCurrentPosition()`方法,不过`getCurrentPosition()`方法只可获取一次当前的位置。
49+
50+
这两个方法都可以接受三个参数,第一个参数为成功时得到位置信息时的回调函数,使用`Position`对象作为唯一的参数。;第二个参数为获取位置信息失败时的回调函数,是一个可选项;第三个参数是一个可选的`PositionOptions`对象。
51+
52+
![data](/images/0707-data.png)
53+
54+
返回的数据中`accuracy`代表位置的精确度;`heading`代表指南针应该所指的角度;`latitude``longitude`分别代表位置的经纬度;`speed`代表当前位置的高度。
55+
56+
这个练习就到这里结束了,主要还是要学会查看文档,不断的自我学习。💪
57+
58+
[MDN](https://developer.mozilla.org/zh-CN/docs/Web/API/Geolocation)

0 commit comments

Comments
 (0)