如何创建Google Map marker自动更新?

时间:2010-07-19 20:27:33

标签: javascript asp.net-mvc google-maps

我正在研究mvc项目,其中包括谷歌地图

我的系统允许用户向系统发送推文并将其保存在数据库中,然后在地图上显示推文

我需要做的是“当系统获取新数据时,在地图上自动更新标记”

有什么建议吗?非常感谢^^

1 个答案:

答案 0 :(得分:4)

在服务器上需要一个脚本,给定一个时间戳将检查在该时间戳之后是否已在数据库中插入新记录。如果是,则脚本应返回包含新信息的响应。

然后,您应该使用normallong polling向服务器端脚本发起AJAX请求,并使用上次更新的timestamp参数。

当您的AJAX请求从服务器接收新信息时,您应该只是将新标记添加到地图中。然后使用更新的时间戳参数启动新的AJAX请求。

使用jQuery的伪示例:

var lastUpdate = ''; // You need to decide what the server should return
                     //  when you load the map the first time.

function autoUpdate() {
  $.ajax({
    type: "GET",
    url: "check_updates.aspx?last_update=" + lastUpdate,
    dataType: 'json',
    success: function(jsonData) {

      // 1. Check if jsonData is empty. If empty skip to 4.
      //    Else we received some fresh data.
      //
      // 2. Update lastUpdate from the jsonData with the timestamp from 
      //    the server. Don't use JavaScript to update the timestamp, 
      //    because the time on the client and on the server will 
      //    never be exactly in sync.
      //
      // 3. Add new markers on Google Map.
      //    
      // 4. Relaunch the autoUpdate() function in 5 seconds.
      setTimeout(autoUpdate, 5000);
    }
  });
}