<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>监听当前位置</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<style>
table {border-collapse: collapse;}
th, td {padding: 4px;}
th {text-align:right;}
.table-container
{
width: 100%;
overflow-y: auto;
_overflow: auto;
margin: 0 0 1em;
}
table{border:0; border-collapse:collapse;}
table td,table th{border:1px solid #999; padding:.5em 1em}
//添加IOS下滚动条
.table-container::-webkit-scrollbar
{
-webkit-appearance: none;
width: 14px;
height: 14px;
}
.table-container::-webkit-scrollbar-thumb
{
border-radius: 8px;
border: 3px solid #fff;
background-color: rgba(0, 0, 0, .3);
}
</style>
</head>
<body>
<div class="table-container">
<table border="1" >
<tr>
<th>经度:</th><td id="longitude">-</td>
</tr>
<tr>
<th>纬度:</th><td id="latitude">-</td>
</tr>
<tr>
<th>海拔:</th><td id="altitude">-</td>
</tr>
<tr>
<th>坐标精度:</th><td id="accuracy">-</td>
</tr>
<tr>
<th>海拔精度:</th><td id="altitudeAccuracy">-</td>
</tr>
<tr>
<th>行进方向:</th><td id="heading">-</td>
</tr>
<tr>
<th>行进速度:</th><td id="speed">-</td>
</tr>
<tr>
<th>时间戳:</th><td id="timestamp">-</td>
</tr>
<tr>
<th>错误码:</th><td id="errcode">-</td>
</tr>
<tr>
<th>错误信息:</th><td id="errmessage">-</td>
</tr>
</table>
<button id="pressme">停止监听</button>
</div>
<script>
var options = {
enableHighAccuracy: true,
timeout: 2000,
maximumAge: 30000
};
var watchID = navigator.geolocation.watchPosition(displayPosition, handleError, options);
document.getElementById("pressme").onclick = function(e) {
navigator.geolocation.clearWatch(watchID);
};
function displayPosition(pos) {
var properties = ["longitude", "latitude", "altitude", "accuracy", "altitudeAccuracy", "heading", "speed"];
for (var i =0; i< properties.length; i++) {
var value = pos.coords[properties[i]];
document.getElementById(properties[i]).innerHTML = value;
}
document.getElementById("timestamp").innerHTML = pos.timestamp;
}
function handleError(err) {
document.getElementById("errcode").innerHTML = err.code;
switch(err.code) {
case 1:
document.getElementById("errmessage").innerHTML = "用户末授权使用地理定位功能";
break;
case 2:
document.getElementById("errmessage").innerHTML = "不能确定位置";
break;
case 3:
document.getElementById("errmessage").innerHTML = "请求位置的尝试已超时";
break;
}
//document.getElementById("errcode").innerHTML = err.code;
//document.getElementById("errmessage").innerHTML = err.message;
}
</script>
</body>
</html>