【问题标题】:How to append markers to google maps using ajax如何使用ajax将标记附加到谷歌地图
【发布时间】:2017-03-27 13:32:26
【问题描述】:

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

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);

【问题讨论】:

    标签: javascript ajax google-maps google-maps-api-3 google-maps-markers


    【解决方案1】:

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

    【讨论】:

    • Grt,这是解决问题的一种方法。但是您的答案并不适合使用 ajax 附加标记
    • 你这样做有什么问题?如果您想要工作代码,请提供minimal reproducible example
    猜你喜欢
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多