单击其他标记时如何关闭带有 Google 地图 API 的信息窗口?

How can I close an infowindow with the Google Maps API when clicking the something else marker?

我希望在单击地图中的其他位置或其他标记时关闭该信息窗口。即,同一时间只有一个信息窗口打开,所有其他信息窗口都关闭。

但是我该怎么做呢?

我的代码:

var map = new google.maps.Map(document.getElementById('map'), options);

addMarker({
  coords: { lat: 62.791711, lng: 22.808479 },
  content: 'test 1'
});
addMarker({
  coords: { lat: 65.799962, lng: 24.497773 },
  content: 'test 2'
});
addMarker({
  coords: { lat: 62.331629, lng: 22.890667 },
  content: 'test 3'
});

function addMarker(props) {
  var marker = new google.maps.Marker({
    position: props.coords,
    map: map
  });

  if (props.content) {
    var infoWindow = new google.maps.InfoWindow({
      content: props.content
    });

    marker.addListener('click', function() {
      infoWindow.open(map, marker);
    });
  }
}

您可以为 infoWindow 使用全局变量并检查它是否已经打开分配。如果这是真的,那么关闭并打开另一个:

var map = new google.maps.Map(document.getElementById('map'), options);
var actInfoWindow;

addMarker({
    coords:{lat:62.791711, lng:22.808479},
    content:'test 1'
});
addMarker({coords:{lat:65.799962, lng:24.497773},
     content:'test 2'
}),
    addMarker({coords:{lat:62.331629, lng:22.890667},
    content:'test 3'
});

function addMarker(props){
    var marker = new google.maps.Marker({
        position:props.coords,
        map:map,
    });

    if(props.content){
        actInfoWindow = new google.maps.InfoWindow({
        content:props.content,
    });

    marker.addListener('click', function(){
        var tempMap = actInfoWindow.getMap();
        if (tempMap !== null && typeof tempMap !== "undefined") {
          actInfoWindow.close();
        }
        actInfoWindow = infoWindow.open(map, marker);
    });
  }

要一次只打开一个信息 window,请创建一个全局变量来保存单个 InfoWindow 实例。

var infoWindow;

然后,在您的初始化函数 (initMap) 中,实例化信息 window:

infoWindow = new google.maps.InfoWindow();

将您的 addMarker 函数更改为以下内容:

function addMarker(props) {
  var marker = new google.maps.Marker({
    position: props.coords,
    map: map
  });

  if (props.content) {
    marker.addListener('click', function() {
      infoWindow.setContent(props.content);
      infoWindow.open(map, marker);
    });
  }
}

并且如果你想在用户点击地图时关闭信息window,你可以将这个事件监听器添加到地图:

map.addListener('click', function() {
    if (infoWindow) infoWindow.close();
});

这里是 a JSBin 一个工作示例。