#第六届英特尔杯全国大学生软件创新大赛博客征集#
Geolocation API关于地理位置信息
¦HEML5 Geolocation API 返回坐标的格式为十进制。确定用户地理位置信息的方式有三种:
使用HTML5 Geolocation API
¦检测浏览器的支持情况
function loadLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(updateLocation); } else{document.getElementById("support").innerHTML="Geolocation is not supported by this browser.";} }
如果浏览器支持,由navigator.geolocation 调用updateLocation函数;如果浏览器不支持,support元素返回提示信息。
¦单次定位请求:
void getCurrentPosition(in PositionCallback successCallback,
in optional PositionErrorCallback errorCallback,
in optional PositionOptions options);
successCallback | 调用位置信息数据并进行处理的函数,必选。 |
errorCallback | 调用失败的处理函数,可选。 |
options | 调整HTML5 Geolocation服务的数据收集方式,可选。 |
navigator.geolocation.getCurrentPosition(updateLocation,handleLocationError,{timeout:10000});为例介绍其常用方法。
function updateLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var accuracy=position.coords.accuracy;
var timestamp=position.coords.timestamp;
document.getElementById("latitude").innerHTML = latitude;
document.getElementById("longitude").innerHTML = longitude;
document.getElementById("accuracy").innerHTML = accuracy;
document.getElementById("timestamp").innerHTML = timestamp;
}
updateLocation()用来更新HTML页面中元素的文本内容。
function handleLocationError(error) {
switch(error.code)
{
case 0:
updateStatus("There was an error while retrieving your location: " + error.message);
break;
case 1:
updateStatus("The user prevented this page from retrieving a location.");
break;
case 2:
updateStatus("The browser was unable to determine your location: " + error.message);
break;
case 3:
updateStatus("The browser timed out before retrieving the location.");
break;
}
}
其中,timeout的单位为ms,告诉浏览器当前位置所允许的最长时间。如果在时间段内未完成计算,调用错误处理程序。
¦重复定位请求:
navigator.geolocation.watchPosition(updateLocation,handleLocationError,{maximumAge:20000});
maximumAge表示浏览器重新计算位置的时间间隔,以ms为单位,默认为0。
实例
¦这是一个小的HEML5应用,叫做“距离跟踪器”,里面用到了重复定位地理位置信息,其源码是在网络上找到的demo,如果哪位童鞋需要,可以留下邮箱,我发给你。
作者
¦学校:北京航天航空大学
¦姓名:彭伟
¦E-mail:786800158@qq.com
¦新浪微博:Way-彭伟 http://weibo.com/pengway
¦微信号:w786800158
图标图像:
