如何使用 ajax 将标记附加到 google 地图

How to append markers to google maps using ajax

所以我正在为我的应用程序创建一个 godview,以便我可以实时查看当前用户,但我遇到了这个问题。我使用 ajax 在加载时渲染我的地图,这将我的 table 中的第一个用户显示为地图上的标记。

function getUsers(){

if (window.XMLHttpRequest){
    var xmlhttp = new XMLHttpRequest();
} else { 
    var xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); 
}

xmlhttp.onreadystatechange = function(){

    if(xmlhttp.statusText === "OK"){

        var China = {lat: 9.081999, lng: -8.675277};
        var image = "node.png";

        var map = new google.maps.Map(mapDiv, {
              zoom: 3,
              center: China,
              draggable: true,
              streetViewControl: true,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            });

        var data = JSON.parse(xmlhttp.responseText);

        for (var i = 0; i < data.length; i++){

            lastid = data[i].lastid;


            marker = new google.maps.Marker({
                position: new google.maps.LatLng(data[i].latitude, data[i].longitude),
                map: map,
                icon: image
            });
        }
    }
}

当应用程序第一次加载时,我得到的只是第一个用户,这很好。随后,我想以一定的时间间隔获取 id 大于第一个最后一个的新用户。

//Php that fetches the new result
    $lastId = $_GET['lastid'];

    $sql = "select * from user where id > '$lastId' limit 1";
    $result = mysqli_query($conn, $sql);

    if($result){

        $count = mysqli_num_rows($result);

        if($count > 0){

            while($row = mysqli_fetch_assoc($result)){

                $user = ['lastid' => $row['id'], 'username' => $row['username'], 'latitude' => $row['latitude'], 'longitude' => $row['longitude']];
            }

            echo json_encode($user);
        }
    }


//Ajax call fetches the new users look something like this
function addNewUser(lastid){


if (window.XMLHttpRequest){
    var xmlhttp = new XMLHttpRequest();
} else { 
    var xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); 
}

xmlhttp.onreadystatechange = function(){

    if(xmlhttp.statusText === "OK"){

        var data = JSON.parse(xmlhttp.responseText);

        lastid = data.lastid;

    }
}

xmlhttp.open('GET', 'fetchusers.php?user&lastid=' + lastid,true);
xmlhttp.send();
}

我尝试传递 lastid,并且 运行 在我的 onload 中使用一些间隔方法来获取最新的。我的困境是将这个新结果作为标记附加到地图上,这样它就可以在不刷新的情况下逐项自动更新。

window.onload = function(){
  getUsers();

  setInterval(() => {
    addNewUser(lastid);
}, 5000);

不要为每个用户创建一个新地图,创建一个全局地图变量,初始化一次,然后将您的用户添加到其中。