HTML5之使用地理位置
1.地理位置
地理位置就是一个由经度和纬度组成的一个坐标(经度,纬度)
- 经度 : 南北极的连接线
- 纬度 : 东西连接的线
2.位置信息从何而来
-
IP地址
-
GPS全球定位系统
-
Wi-Fi无线网络
-
基站
3.API
HTML5 Geolocation(地理定位)用于定位用户的位置。
navigator.geolocation
单次定位请求 :getCurrentPosition(请求成功(function),请求失败(function),数据收集方式)
请求成功函数:{
经度 : coords.longitude
纬度 : coords.latitude
准确度 : coords.accuracy
海拔 : coords.altitude
海拔准确度 : coords.altitudeAcuracy
行进方向 : coords.heading
地面速度 : coords.speed
请求的时间: new Date(position.timestamp)
}
请求失败函数{
失败编号 :code
0 : 不包括其他错误编号中的错误
1 : 用户拒绝浏览器获取位置信息
2 : 尝试获取用户信息,但失败了
3 : 设置了timeout值,获取位置超时了
}多次定位请求 : watchPosition ( 参数和静态的定位请求一样 )
移动设备有用,位置改变才会触发
配置参数:frequency 更新的频率
关闭更新请求 : clearWatch
实例Demo
html
<p style="display: inline-block">当前的位置:</p>
<input type="button" value="获取位置" onclick="getLocation()" />
<p id="errMsg"></p>
<ul>
<li id="longitude"></li>
<li id="latitude"></li>
</ul>
javascript
let oUl = document.querySelector("ul");
let oLongitude = document.querySelector("#longitude"); //经度
let oLatitude = document.querySelector("#latitude"); //纬度
let errMsg = document.querySelector("#errMsg");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showLocation, showError);
} else {
alert("不支持浏览器定位");
}
}
function showLocation(position) {
errMsg.innerHTML = '';
oLongitude.innerHTML = `经度:${position.coords.longitude}`;
oLatitude.innerHTML = `纬度:${position.coords.latitude}`;
}
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
errMsg.innerHTML = "用户拒绝对获取地理位置的请求。";
break;
case error.POSITION_UNAVAILABLE:
errMsg.innerHTML = "位置信息是不可用的。";
break;
case error.TIMEOUT:
errMsg.innerHTML = "请求用户地理位置超时。";
break;
case error.UNKNOWN_ERROR:
errMsg.innerHTML = "未知错误。";
break;
}
}
这里需要注意一小点: