在第一次点击谷歌地图信息窗口没有打开,它在第二次点击时打开只通过ajax调用,在V3

时间:2013-05-24 06:06:57

标签: google-maps google-maps-api-3 google-maps-markers infowindow

我使用下面的代码通过ajax调用在我的地图中打开一个infowindow

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调用点击标记,infowindow的内容作为响应。 在第二次单击时,infowindow将打开。下一次,点击加载infowindow的标记即可。
以前有人有过这个错误吗?有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分: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');
}

答案 1 :(得分: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;
});
}