地理位置(Geolocation)是 HTML5 的重要特性之一,提供了确定用户位置的功能,借助这个特性能够开发基于位置信息的应用。
HTML5 Geolocation API 使用非常简单,基本调用方式如下:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(locationSuccess, locationError,{
// 指示浏览器获取高精度的位置,默认为false
enableHighAcuracy: true,
// 指定获取地理位置的超时时间,默认不限时,单位为毫秒
timeout: 5000,
// 最长有效期,在重复获取地理位置时,此参数指定多久再次获取位置。
maximumAge: 3000
});
}else{
alert("Your browser does not support Geolocation!");
}
locationError为获取位置信息失败的回调函数,可以根据错误类型提示信息:
locationError: function(error){
switch(error.code) {
case error.TIMEOUT:
showError("A timeout occured! Please try again!");
break;
case error.POSITION_UNAVAILABLE:
showError('We can\'t detect your location. Sorry!');
break;
case error.PERMISSION_DENIED:
showError('Please allow geolocation access for this to work.');
break;
case error.UNKNOWN_ERROR:
showError('An unknown error occured!');
break;
}
}
locationSuccess为获取位置信息成功的回调函数,返回的数据中包含经纬度等信息。
locationSuccess: function(position){
var coords = position.coords;
// 维度
alert(coords.latitude);
// 精度
alert( coords.longitude);
}
Geolocation 对象 - 其他的方法
watchPosition() - 返回用户的当前位置,并继续返回用户移动时的更新位置(就像汽车上的 GPS)。
clearWatch() - 停止 watchPosition() 方法
watchPosition和clearWatch()是一对方法,起原理和setTimeout方法相同。watchPosition方法会返回一个唯一的标识,clearWatch可通过这个唯一标识清除watchPosition方法的监听。
watchPosition的语法和getCurrentPosition相同,可以传递3个参数分别为:
1.监听成功后返回的函数
2.监听失败返回的函数
3.可选参数
<script>
var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.watchPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
x.innerHTML="Latitude: " + position.coords.latitude +
"<br />Longitude: " + position.coords.longitude;
}
</script>
自己使用的例子
function getLocation() {
if (window.navigator.geolocation) {
var options = {
enableHighAccuracy : true,
};
window.navigator.geolocation.getCurrentPosition(function(position) {
var lng = position.coords.longitude;
var lat = position.coords.latitude;
getXq(lng, lat);
}, function(error) {
getXq('116.307852', '40.057031');
}, options);
} else {
alert("浏览器不支持html5来获取地理位置信息");
}
}
本文介绍了HTML5 Geolocation API的基本使用方法,包括如何获取用户的地理位置信息,如何处理获取过程中可能出现的各种错误情况,以及如何利用该API实现位置信息的持续更新。
291

被折叠的 条评论
为什么被折叠?



