JavaScript定时获取用户位置信息label输出换行显示问题求助
问题原因
- HTML 中普通空白字符不会触发内容换行,需要显式插入换行标签
<br>才能让新记录另起一行展示 - 原有代码每次更新内容时使用
.textContent读取已有内容,会把 HTML 标签转义为纯文本,导致换行标签无法生效 - 额外错误点:位置获取失败的回调函数中引用了页面不存在的
Latitude、Longitude元素,运行时会抛出JS报错
修改方案
核心修改点
- 统一使用
.innerHTML读写地址展示元素的内容,保证 HTML 标签可以正常解析 - 每拼接完一条完整的位置记录后,在末尾追加
<br>标签实现换行 - 修复位置获取失败回调的报错问题
- 若需要每5分钟获取一次位置,将定时器间隔从
1000 * 5(5秒)改为1000 * 60 *5(5分钟)
修改后完整代码
<!DOCTYPE html> <html> <head> <title> Location Test </title> <link rel="shortcut icon" href="#"> </head> <body> <h1> Location </h1> <label id = "Address"> </label> <br> <input type="button" value="Log Out" id="LogOut"> <script> const logoutButton = document.getElementById("LogOut"); const addrEle = document.getElementById("Address"); // 提前缓存DOM元素,避免重复查询 function getLocation() { navigator.geolocation.getCurrentPosition( function(Position) { var currentdate = new Date(); // 先拼接单条记录的基础内容 var record = "Last Sync: " + currentdate.getDate() + "/" + (currentdate.getMonth() + 1) + "/" + currentdate.getFullYear() + ". " + currentdate.getHours() + ":" + currentdate.getMinutes() + "." + currentdate.getSeconds() + ". "; record += "Latitude: " + Position.coords.latitude; record += " Longitude: " + Position.coords.longitude; record += " Accuracy: " + Position.coords.accuracy; record += " Heading towards direction: " + Position.coords.heading; record += " Speed: " + Position.coords.speed; var api_key = '206170168bcf4fdf905d85a34f7b3d79'; var latitude = Position.coords.latitude; var longitude = Position.coords.longitude; var api_url = 'https://api.opencagedata.com/geocode/v1/json' var request_url = api_url + '?' + 'key=' + api_key + '&q=' + encodeURIComponent(latitude + ',' + longitude) + '&pretty=1' + '&no_annotations=1'; var request = new XMLHttpRequest(); request.open('GET', request_url, true); request.onload = function() { if (request.status === 200) { var data = JSON.parse(request.responseText); record += " Address: " + data.results[0].formatted + "<br>"; // 末尾追加换行标签 addrEle.innerHTML += record; // 直接追加到现有内容 } else if (request.status <= 500) { console.log("unable to geocode! Response code: " + request.status); var data = JSON.parse(request.responseText); console.log('error msg: ' + data.status.message); } else { console.log("server error"); } }; request.onerror = function() { console.log("unable to connect to server"); }; request.send(); }, function(PositionError) { // 修复不存在元素的报错问题 console.log("位置获取失败:", PositionError.message); }) } getLocation(); setInterval(getLocation, 1000 * 60 * 5); // 每5分钟获取一次位置 logoutButton.addEventListener("click", (e) => { e.preventDefault(); getLocation(); window.location.href = "login.html"; }) </script> </body> </html>
内容的提问来源于stack exchange,提问作者BeginnerProgrammer
相关产品推荐
相关产品推荐

