当前位置: 网学 > 编程文档 > XHTML > 正文

html5指南-4.使用Geolocation实现定位功能

来源:Http://myeducs.cn 联系QQ:点击这里给我发消息 作者: 用户投稿 来源: 网络 发布时间: 13/07/26

鉴于大家对XHTML十分关注,我们编辑小组在此为大家搜集整理了“html5指南-4.使用Geolocation实现定位功能”一文,供大家参考学习!

今天我们要学习的是使用Geolocation实现定位功能。我们可以通过navigator.geolocation获取Geolocation对象,他提供了下列方法:
getCurrentPosition(callback,errorCallback,options):获取当前位置;
watchPosition(callback,error,options):开始监控当前位置;
clearWatch(id):停止监控当前位置。
note:下面例子使用的浏览器是chrome,使用其他浏览器我不能保证运行结果和例子显示的结果一致。
1.获取当前位置
我们将使用getCurrentPosition方法获取当前位置,位置信息不会以结果的形式直接返回,我们需要使用callback函数进行处理。在获取坐标的过程中会有些延迟,还会问你要访问权限。我们来看下面的例子:

复制代码代码如下:
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
<style>
table{border-collapse: collapse;}
th, td{padding: 4px;}
th{text-align: right;}
</style>
</head>
<body>
<table border="1">
<tr>
<th>Longitude:</th>
<td id="longitude">-</td>
<th>Latitude:</th>
<td id="latitude">-</td>
</tr>
<tr>
<th>Altitude:</th>
<td id="altitude">-</td>
<th>Accuracy:</th>
<td id="accuracy">-</td>
</tr>
<tr>
<th>Altitude Accuracy:</th>
<td id="altitudeAccuracy">-</td>
<th>Heading:</th>
<td id="heading">-</td>
</tr>
<tr>
<th>Speed:</th>
<td id="speed">-</td>
<th>Time Stamp:</th>
<td id="timestamp">-</td>
</tr>
</table>
<script>
navigator.geolocation.getCurrentPosition(displayPosition);
function displayPosition(pos) {
var properties = [''longitude'', ''latitude'', ''altitude'', ''accuracy'', ''altitudeAccuracy'', ''heading'', ''speed''];
for (var i = 0, len = properties.length; i < len; i++) {
var value = pos.coords[properties[i]];
document.getElementById(properties[i]).innerHTML = value;
}
document.getElementById(''timestamp'').innerHTML = pos.timestamp;
}
</script>
</body>
</html>

返回的position对象包含两个属性,coords:返回坐标信息;timestamp:获取坐标信息的时间。其中coords又包括下面属性:latitude:纬度;longitude:经度;altitude:高度;accuracy:精确度(米);altitudeAccuracy:高度精确度(米);heading:行进方向;speed:行进速度(米/秒)。
并不是所有的信息都会返回,这取决于你承载浏览器的设备。像有GPS、加速器、罗盘的移动设备会返回大部分信息,家用电脑就不行了。家用电脑获取的位置信息,取决于所处的网络环境或者是wifi。下面我们看上例的运行结果。


点击允许,获取坐标信息。

2.处理异常
现在我们介绍getCurrentPosition的异常处理,他是通过使用errorCallback回调函数实现的。函数返回的参数error包含两个属性,code:错误类型的代码;message:错误信息。code包含三个值:1:用户没有授权使用geolocation;2:无法获取坐标信息;3:获取信息超时。
下面我们看个例子:

复制代码代码如下:
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
<style>
table{border-collapse: collapse;}
th, td{padding: 4px;}
th{text-align: right;}
</style>
</head>
<body>

网学推荐

免费论文

原创论文

浏览:
设为首页 | 加入收藏 | 论文首页 | 论文专题 | 设计下载 | 网学软件 | 论文模板 | 论文资源 | 程序设计 | 关于网学 | 站内搜索 | 网学留言 | 友情链接 | 资料中心
版权所有 QQ:3710167 邮箱:3710167@qq.com 网学网 [Myeducs.cn] 您电脑的分辨率是 像素
Copyright 2008-2015 myeducs.Cn www.myeducs.Cn All Rights Reserved
湘ICP备09003080号