概念

Geolocation 接口是一个用来获取设备地理位置的可编程的对象,它可以让 Web 内容访问到设备的地理位置,这将允许 Web 应用基于用户的地理位置提供定制的信息。说实话:其实Geolocation 就是用来获取到当前设备的经纬度(位置)

方法

获取地址坐标

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
* @Author: gaocaipeng
* @Date: 2021-09-18 09:37:31
* @Last Modified by: gaocaipeng
* @Last Modified time: 2021-09-18 09:37:31
*/
window.geoLocation = (() => {
class Location {
constructor() {
this.geolocation = null;
this.init();
}
init() {
if (navigator.geolocation) {
this.geolocation = window.navigator.geolocation;
this.getCurrentLocation();
}
}
handlerSuccess(position) {
console.log(position.coords.latitude, position.coords.longitude);
}
handlerFaild({ code }) {
let msg = "";
switch (code) {
case 1:
msg = "用户拒绝了位置服务";
alert(msg);
break;

case 2:
msg = "获取不到位置信息";
alert(msg);
break;

case 3:
msg = "获取信息超时";
alert(msg);
break;
}
return new Error(msg);
}
getCurrentLocation() {
this.geolocation.getCurrentPosition(
this.handlerSuccess,
this.handlerSuccess
);
}
}
return new Location();
})();
console.log(geoLocation);

项目地址:

请访问:https://github.com/76351506/geolocaiton