<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
/**
* 地理定位
*
* navigator ˈnævɪgeɪtə(r) (兰微给特) n. 领航员
* navigator是在JavaScript中的一个独立的对象,他用于提供用户所使用的浏览器以及操作系统等信息,以navigator对象属性的形式来提供
*
* Navigator 对象包含有关浏览器的信息。
* 注释:没有应用于 navigator 对象的公开标准,不过所有浏览器都支持该对象
*/
function getLocation() {
//判断浏览器是否支持html5地理定位
//地理位置(Geolocation)是 HTML5 的重要特性之一,提供了确定用户位置的功能,借助这个特性能够开发基于位置信息的应用
if (navigator.geolocation) {
//定位方法,参数1:定位成功回调函数,参数2:定位失败回调函数,参数3:具体定位设置
navigator.geolocation.getCurrentPosition(showMap,handlerError,{
enableHighAccuracy:true, //是否高精度定位
maximumAge:1000 //每隔多少毫秒重新获得一次位置
});
} else {
alert('当前浏览器不支持html5的地理定位');
}
}
/**
* 定位成功的回调函数,参数就是坐标对象
*/
function showMap(loc) {
var longitude = loc.coords.longitude;//经度
var latitude = loc.coords.latitude;//纬度
alert('定位成功,当前经纬度:' + longitude + ',' + latitude);
}
/**
* 定位失败的回调函数,参数就是错误码对象
*/
function handlerError(err) {
if (err.code == 1) {
alert('位置服务被拒绝,请开启');
} else if (err.code == 2) {
alert('无法获得用户位置');
} else if (err.code == 3) {
alert('获取信息超时');
} else if (err.code == 4) {
alert('未知错误无法定位');
}
}
//调用定位
getLocation();
</script>
</body>
</html>