版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/aduovip/article/details/53415474
GeoLocation API 通常用于移动设备获取地理位置,严格来说,它并不属于H5的标准规范.
一 如何使用 GeoLocation API?
要使用该API, 通过window.navigator.geolocatio 获得 对地理定位的访问。 该对象有如下三个方法:
1. getCurrentPosition()
2. watchPosition()
3. clearWatch()
getCurrentPosition()方法 可以传递三个参数, 如下所示:
void getCurrentPosition(PositionCallback successCallback, optional PositionErrorCallback errorCallback, optional PositionOptions options);
其中第一个参数为必选参数,后面两个为可选参数
看一个示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>GeoLocation API 地理定位</title>
<script type="text/javascript">
window.navigator.geolocation.getCurrentPosition(function(pos){
alert("当前地理位置的纬度: " +pos.coords.latitude
+"\n当前地理位置的经度: " +pos.coords.longitude
+ "\n当前经纬度的精度: " +pos.coords.accuracy
+ "\n设备的当前运动方向: " +pos.coords.heading
+ "\n设备的当前速度: " +pos.coords.speed
);
});
var watchID= window.navigator.geolocation.watchPosition(function(pos){
alert("当前位置变化的纬度: " +pos.coords.latitude
+"\n当前位置变化的经度: " +pos.coords.longitude
+ "\n当前经纬度变化的精度: " +pos.coords.accuracy
+ "\n设备的当前运动方向: " +pos.coords.heading
+ "\n设备的当前变化的速度: " +pos.coords.speed);
navigator.geolocation.clearWatch(watchID);
}, function(){
});
</script>
</head>
<body>
</body>
</html>
调用getCurrentPosition() 成功后,回调的函数中,可以通过其中的参数对象, 获得当前用户访问Web 页面时的地理位置信息
pos 对象包含一个coords 属性, coords 属性表示一系列的地理坐标信息.
latitude: 纬度 (十进制)
longitude: 经度(十进制)
altitude: 高度
acuracy: 经纬度坐标的精度 (米为单位)
altitudeAccuracy: 以米为单位的高度坐标精度水平
heading: 运动的方向 (通过相对正北做顺时针旋转的角度指定)
speed: 当前地面速度(m/s 为单位)
pos 还包含一个 timestamp 属性,该属性用于返回 coords 对象时以毫秒为单位创建时间戳。
效果图如下: