0

我正在使用下面的代码通过 ajax 调用在我的地图中打开一个信息窗口

var openedInfoWindow = null; 
var infoWindow = new google.maps.InfoWindow();

function profileInitialiser(marker, location) {
google.maps.event.addListener(marker, 'click', function(){
        new Ajax.Request('/ajax/', {
        parameters: {'action':'profileInfo', 'id':location.id},
        onSuccess: function(transport){
            addInfoWindow(marker, transport.responseText, location.id);
        }
    });
});
}

function addInfoWindow(marker, content, id) {
  google.maps.event.addListener(marker, 'click', function () {
    if (openedInfoWindow != null) {
        openedInfoWindow.close(); 
    } 
    infoWindow.setContent(content);
    infoWindow.open(this.map, marker);
    openedInfoWindow = infoWindow;  
    google.maps.event.addListener(infoWindow, 'closeclick', function() {
    openedInfoWindow = null;
    });
});
}

上面的代码,profileInitialiser 函数在加载谷歌地图中的标记时调用。第一时间,首先通过ajax调用点击标记,信息窗口的内容作为响应来。在第二次单击中,信息窗口将打开。下一次,单击加载信息窗口的标记是第一次单击。
有没有人以前有过这个错误?有人可以帮我解决这个问题吗?

4

2 回答 2

0

当数据从服务器返回时,您的 AddInfoWindow 函数只是将单击侦听器添加到标记。您还应该使用内容打开 infoWindow。

var openedInfoWindow = null; 
var infoWindow = new google.maps.InfoWindow();

function profileInitialiser(marker, location) {
// only do this on the first click
google.maps.event.addListenerOnce(marker, 'click', function(){
        new Ajax.Request('/ajax/', {
        parameters: {'action':'profileInfo', 'id':location.id},
        onSuccess: function(transport){
            addInfoWindow(marker, transport.responseText, location.id);
        }
    });
});
}

function addInfoWindow(marker, content, id) {
  // display the content when the marker is clicked        
  google.maps.event.addListener(marker, 'click', function () {
    if (openedInfoWindow != null) {
        openedInfoWindow.close(); 
    } 
    infoWindow.setContent(content);
    infoWindow.open(this.map, marker);
    openedInfoWindow = infoWindow;  
    google.maps.event.addListener(infoWindow, 'closeclick', function() {
    openedInfoWindow = null;
    });
  });
  // click on the marker to display the newly added infowindow
  google.maps.event.trigger(marker, 'click');
}
于 2013-05-24T06:51:22.867 回答
0

为什么要添加两次单击事件侦听器。只需从 addInfoWindow 函数中删除侦听器即可。

这是代码:

function addInfoWindow(marker, content, id) {

if (openedInfoWindow != null) {
    openedInfoWindow.close(); 
} 
infoWindow.setContent(content);
infoWindow.open(this.map, marker);
openedInfoWindow = infoWindow;  
google.maps.event.addListener(infoWindow, 'closeclick', function() {
openedInfoWindow = null;
});
}
于 2013-05-27T06:05:26.727 回答