出现第二个时关闭第一个infowindow

时间:2014-05-12 06:08:29

标签: javascript html google-maps google-maps-api-3 infowindow

function showpopup(lat, lng, info)
    {

        // Create infoWindow
        var infoWindow = new google.maps.InfoWindow({
            content: info
        });

    // Create marker
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(lat, lng),
            title: 'Lima',
            map: map.map,
            infoWindow: infoWindow
        });

    // This opens the infoWindow
        infoWindow.open(map, marker);
    }

我有这个功能,需要三个参数并在地图上创建信息窗口但现在我想要当用户打开第二个信息窗口时第一个关闭使用javascript和Gmap V3

2 个答案:

答案 0 :(得分:1)

您可以使用全局变量来跟踪infowindow并在使用close()方法打开新窗口之前将其关闭,例如

var infoWindow; //global tracker
function showpopup(lat, lng, info)
{
 //close info window in it exists   
if(infoWindow)
infoWindow.close();
// Create new infoWindow
     infoWindow = new google.maps.InfoWindow({
        content: info
    });

// Create marker
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lng),
        title: 'Lima',
        map: map.map,
        infoWindow: infoWindow
    });

// This opens the infoWindow
    infoWindow.open(map, marker);
}

如果有多个信息窗口,您可以拥有一个数组,循环遍历它们并在每个项目上调用close()方法..

答案 1 :(得分:0)

试试这段代码..

var infowindows = new Array();
var popup = new google.maps.InfoWindow({
  // size: new google.maps.Size(420,130),
    content:content_info
});
infowindows.push(popup); //push all infoboxes to an array

google.maps.event.addListener(marker, 'click', function() {
    close_popups();    //close any infobox open
    map.panTo(mycenter1);
    popup.open(map, marker); //opens current marker's infowindow


    // currentPopup = null;
  });

function close_popups(){
  for(var i = 0; i<infowindows.length; i++){
    infowindows[i].close();
  }
}