Google Maps V3:定期更新标记

Posted

技术标签:

【中文标题】Google Maps V3:定期更新标记【英文标题】:Google Maps V3: Updating Markers Periodically 【发布时间】:2012-03-26 10:28:11 【问题描述】:

我在谷歌地图上找到了 php/mysql 教程 here

我希望每 5 秒左右从数据库中更新一次标记。

据我了解,我需要使用 Ajax 定期更新标记,但我很难理解在哪里添加函数以及在哪里使用 setTimeout()

我发现的所有其他示例并不能真正解释发生了什么,一些有用的指导会很棒!

这是我的代码(与 Google 示例相同,但有一些 var 更改):

function load() 
  var map = new google.maps.Map(document.getElementById("map"), 
    center: new google.maps.LatLng(37.80815648152641, 140.95355987548828),
    zoom: 13,
    mapTypeId: 'roadmap'
  );
  var infoWindow = new google.maps.InfoWindow;

  // Change this depending on the name of your PHP file

  downloadUrl("nwmxml.php", function(data) 
    var xml = data.responseXML; 
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) 
      var host = markers[i].getAttribute("host");
      var type = markers[i].getAttribute("active");
      var lastupdate = markers[i].getAttribute("lastupdate");
      var point = new google.maps.LatLng(
          parseFloat(markers[i].getAttribute("lat")),
          parseFloat(markers[i].getAttribute("lng")));
      var html = "<b>" + "Host: </b>" + host + "<br>" + "<b>Last Updated: </b>" + lastupdate + "<br>";
      var icon = customIcons[type] || ;
      var marker = new google.maps.Marker(
        map: map,
        position: point,
        icon: icon.icon,
        shadow: icon.shadow
      );
      bindInfoWindow(marker, map, infoWindow, html);

    

  );


function bindInfoWindow(marker, map, infoWindow, html) 
  google.maps.event.addListener(marker, 'click', function() 
    infoWindow.setContent(html);
    infoWindow.open(map, marker);
  );


function downloadUrl(url, callback) 
  var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
      new XMLHttpRequest;

  request.onreadystatechange = function() 
    if (request.readyState == 4) 
      request.onreadystatechange = doNothing;
      callback(request, request.status);
    
  ;

  request.open('GET', url, true);
  request.send(null);


function doNothing() 

希望有人能帮帮我!

【问题讨论】:

【参考方案1】:

请注意,我没有对此进行测试,因为我没有带 xml 的数据库

首先,您需要将 load() 函数拆分为一个初始化地图并在 domready 上加载标记的函数,以及一个稍后将用于处理 xml 并更新地图的函数。需要这样做,这样您就不会在每次加载时都重新初始化地图。

其次,您需要决定如何处理已在地图上绘制的标记。为此,您需要在将它们添加到地图时将它们添加到数组中。在第二次更新时,您可以选择重绘标记(重建数组)或简单地更新现有数组。我的示例显示了您只需从屏幕上清除旧标记的场景(这更简单)。

//global array to store our markers
    var markersArray = [];
    var map;
    function load() 
        map = new google.maps.Map(document.getElementById("map"), 
            center : new google.maps.LatLng(37.80815648152641, 140.95355987548828),
            zoom : 13,
            mapTypeId : 'roadmap'
        );
        var infoWindow = new google.maps.InfoWindow;

        // your first call to get & process inital data

        downloadUrl("nwmxml.php", processXML);
    

    function processXML(data) 
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName("marker");
        //clear markers before you start drawing new ones
        resetMarkers(markersArray)
        for(var i = 0; i < markers.length; i++) 
            var host = markers[i].getAttribute("host");
            var type = markers[i].getAttribute("active");
            var lastupdate = markers[i].getAttribute("lastupdate");
            var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
            var html = "<b>" + "Host: </b>" + host + "<br>" + "<b>Last Updated: </b>" + lastupdate + "<br>";
            var icon = customIcons[type] || ;
            var marker = new google.maps.Marker(
                map : map,
                position : point,
                icon : icon.icon,
                shadow : icon.shadow
            );
            //store marker object in a new array
            markersArray.push(marker);
            bindInfoWindow(marker, map, infoWindow, html);


        
            // set timeout after you finished processing & displaying the first lot of markers. Rember that requests on the server can take some time to complete. SO you want to make another one
            // only when the first one is completed.
            setTimeout(function() 
                downloadUrl("nwmxml.php", processXML);
            , 5000);
    

//clear existing markers from the map
function resetMarkers(arr)
    for (var i=0;i<arr.length; i++)
        arr[i].setMap(null);
    
    //reset the main marker array for the next call
    arr=[];

    function bindInfoWindow(marker, map, infoWindow, html) 
        google.maps.event.addListener(marker, 'click', function() 
            infoWindow.setContent(html);
            infoWindow.open(map, marker);
        );
    

    function downloadUrl(url, callback) 
        var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;

        request.onreadystatechange = function() 
            if(request.readyState == 4) 
                request.onreadystatechange = doNothing;
                callback(request, request.status);
            
        ;

        request.open('GET', url, true);
        request.send(null);
    

【讨论】:

感谢 Michal,解释得很好,地图已显示,但我无法显示节点,Here 是我的完整页面再次感谢! 能否请您发布您的示例 xml(也许值得 2 次更新,以便我可以调试它) 当然 XML Sample 1 , XML Sample 2 位置不会经常变化,但是 active 的值会:) Firebug 返回: data is not defined - downloadUrl("nwmxml.php", processXML(data)); 似乎无法从 php 脚本中获取 XML 数据? 我编辑了脚本——我的错误是 downloadUrl("nwmxml.php", processXML(data));应该是 downloadUrl("nwmxml.php", processXML);并且 map 变量在范围内应该是全局的【参考方案2】:
setInterval(function()  
    downloadUrl("conection/cargar_tecnicos.php", function(data) 

        var xml = data.responseXML;
         markers = xml.documentElement.getElementsByTagName("marker");
         removeAllMarkers();
        for (var i = 0; i < markers.length; i++) 
              var name = markers[i].getAttribute("name");
            var fecha = markers[i].getAttribute("fecha");
            var id_android = markers[i].getAttribute("id_android");
            var celular = markers[i].getAttribute("celular");
            var id = markers[i].getAttribute("id");
            var logo = markers[i].getAttribute("logo");
            var type = markers[i].getAttribute("type");
            var point = new google.maps.LatLng(
                    parseFloat(markers[i].getAttribute("lat")),
                    parseFloat(markers[i].getAttribute("lng")));

           var html = "<div class='infowindow'>"
                        +"<br/><div style='text-align:center;'><img src="+logo+"><br/>"    
                        +"<b>" + name + "</b></div><br/>"
                        +"<br/><label><b>Celular:</b></label>" + celular+""
                        +"<br/><label><b>Id Android:</b></label>" + id_android+""
                        +"<br/><label><b>Fecha y Hora:</b></label>" + fecha+""
                        +"<br/><br/><div style='text-align:center;'><a><input style=';' id='pop' type='image' value='"+id+"' class='ASD' img src='img/vermas.png' title='Detalles'/></a></div></div>";
            var icon = customIcons[type] || ;
             marker[i] = new google.maps.Marker( 
                position: point,
                icon: icon.icon,
                shadow: icon.shadow,
                title:name
            );

            openInfoWindow(marker[i], map, infoWindow, html);   
          marker[i].setMap(map);
        
    );

,10000);

function removeAllMarkers()// removes all markers from map
    for( var i = 0; i < marker.length; i++ )
            marker[i].setMap(null);


【讨论】:

以上是关于Google Maps V3:定期更新标记的主要内容,如果未能解决你的问题,请参考以下文章

Google Maps api V3 更新标记

Google Maps Javascript API V3中的旋转标记

Google Maps v3 在地图初始化后调整缩放级别

Google Maps Api v3 - 如何删除集群图标?

google maps js v3 api教程 -- 在地图上添加标记

在 Google Maps API v3 中删除标记