Google Maps V3:通过AJAX加载infowindow内容

mik*_*son 38 jquery google-maps google-maps-api-3

使用ajax将内容加载到我的infowindow的最佳方法是什么?现在我使用iframe得到类似的效果,但我并不满意.我认为这将是直截了当的,但由于某种原因令我感到困惑.这就是它现在的工作方式:

var markers = [];
  var infowindow = new google.maps.InfoWindow();
  $.each(JSON.parse(aulas), function(i, a){

    var latlng = new google.maps.LatLng(a.aula.lat, a.aula.lng);
    var marker = new google.maps.Marker({
      position : latlng,
      title: a.aula.title
    });

    google.maps.event.addListener(marker, 'click', function() {
      infowindow.close();
      infowindow.setContent("<div class='infowindow_content'><iframe src='aulas/show/" + a.aula.id + "'></iframe</div>");

      infowindow.open(map, marker);
    });
    markers.push(marker);
  });
Run Code Online (Sandbox Code Playgroud)

在infowindow.setContent调用之前通过ajax获取内容很容易,但我想只在infowindow打开时才进行ajax调用.有什么想法吗?

顺便说一句:我正在使用jQuery.

正如在答案中所建议的那样,我决定将调用移到setContent并打开一个单独的函数.对于那些感兴趣的人,解决这个的代码是:

function load_content(marker, id){
  $.ajax({
    url: 'aulas/show/' + id,
    success: function(data){
      infowindow.setContent(data);
      infowindow.open(map, marker);
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

然后改变监听器:

    google.maps.event.addListener(marker, 'click', function() {
      infowindow.close();
      load_content(marker, a.aula.id);
    });
    markers.push(marker);
  });
Run Code Online (Sandbox Code Playgroud)

Red*_*ing 31

您可以在显示信息窗口后的任何时刻调用infowindow.setContent.因此,您最初可以使用微调器设置信息窗口内容,进行AJAX调用(来自事件处理程序),然后使用适当的数据再次从AJAX响应调用infowindow.setContent.