You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript定时获取地理位置如何在label标签换行展示更新记录

修改方案

你需要修正两个核心问题:

  1. 原代码每次拼接内容时取textContent,会过滤掉之前插入的HTML换行标签<br>,导致换行失效
  2. 每次完整记录追加完成后,手动加<br>标签实现换行

具体修改点

  • 将所有重复操作DOM的拼接逻辑优化,先拼接好单条记录的完整内容,再一次性追加到Address元素中
  • 每条记录末尾添加<br>实现换行
  • 修正原错误回调中引用不存在的Latitude、Longitude元素的问题,避免控制台报错

修改后的完整代码

<!DOCTYPE html>
<html>
<head>
    <title> Location Test </title>
    <link rel="shortcut icon" href="#">
</head>
<body>
    <h1> Location </h1>
    <!-- 也可以把label换成div,更适合多行文本展示 -->
    <label id="Address"> </label>
    <br>
    <input type="button" value="Log Out" id="LogOut">
    <script>
        const logoutButton = document.getElementById("LogOut");
        const addressEl = document.getElementById("Address");

        function getLocation() {
            navigator.geolocation.getCurrentPosition(
                function(Position) {
                    var currentdate = new Date();
                    // 先拼接待插入的内容
                    let recordContent = `Last Sync: ${currentdate.getDate()}/${currentdate.getMonth() + 1}/${currentdate.getFullYear()}. ${currentdate.getHours()}:${currentdate.getMinutes()}.${currentdate.getSeconds()}. `;
                    recordContent += `Latitude: ${Position.coords.latitude} `;
                    recordContent += `Longitude: ${Position.coords.longitude} `;
                    recordContent += `Accuracy: ${Position.coords.accuracy} `;
                    recordContent += `Heading towards direction: ${Position.coords.heading} `;
                    recordContent += `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);
                            recordContent += `Address: ${data.results[0].formatted}`;
                        } 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);
                            recordContent += "Address: 解析失败";
                        } else {
                            console.log("server error");
                            recordContent += "Address: 服务器错误";
                        }
                        // 内容拼接完成后追加,末尾加<br>换行
                        addressEl.innerHTML += recordContent + '<br>';
                    };
                    request.onerror = function() {
                        console.log("unable to connect to server");
                        recordContent += "Address: 网络请求失败";
                        addressEl.innerHTML += recordContent + '<br>';
                    };
                    request.send();
                },
                function(PositionError) {
                    // 修正原代码引用不存在元素的问题
                    addressEl.innerHTML += `获取位置失败:${PositionError.message}<br>`;
                })
        }
        getLocation();
        setInterval(getLocation, 1000 * 60 * 5)
        logoutButton.addEventListener("click", (e) => {
            e.preventDefault();
            window.location.href = "login.html";
        }) 
    </script>
</body>
</html>

内容的提问来源于stack exchange,提问作者BeginnerProgrammer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 15:18:05