<!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>