You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Maps API如何获取标记列表 实现点击标记关闭其余信息窗口

解决思路

共有两种成熟可行的实现方案,优先推荐第一种复用信息窗的方案,内存占用更低性能更好。

方案1:复用单个全局InfoWindow(官方推荐)

Google Maps官方推荐全局仅创建一个InfoWindow实例,点击不同标记时动态更新其内容即可,此时打开新弹窗会自动关闭之前打开的弹窗,无需手动遍历关闭。

实现逻辑:

  • 外层作用域仅初始化一次InfoWindow,不需要每次创建标记时生成新实例
  • 点击标记时,直接调用setContent()方法更新信息窗内容,再调用open方法弹出即可

修改后参考代码:

// 外层作用域只初始化一次共享信息窗
let infowindow = new google.maps.InfoWindow({
  zIndex: 2,
  maxWidth: 500,
});

function addMarker({maps,map,position,html,image,center,allowClick,location}){
  // 生成当前标记对应的信息窗内容
  const newHtml = `
  <div style="background-color:white;width:300px;height:250px;border-radius:8px;box-shadow:0 2px 7px 1px rgb(0 0 0 / 30%);box-sizing: border-box;overflow: hidden;padding:12px">
    ${location.name}<br>
    ${location.phone}<br>
    ${location.address}
  </div>`;

  const marker = new maps.Marker({
    map,
    position,
    icon: image,
  });
  
  if(allowClick){
    maps.event.addListener(marker, "click", function(arg) {
      // 动态更新信息窗内容
      infowindow.setContent(newHtml);
      // 打开信息窗,旧弹窗会自动关闭
      infowindow.open(map, marker);
      
      if(center){
        map.setCenter(marker.getPosition());
      }
    });
  }
  
  return marker;
}

方案2:自行维护标记数组手动关闭

如果业务场景需要每个标记保留独立的InfoWindow实例,可以自己维护全局的标记数组替代已废弃的.markers属性:

实现逻辑:

  • 外层作用域定义数组存储所有生成的标记实例
  • 点击标记时遍历数组,调用每个标记绑定的infowindow的close方法,再打开当前标记的弹窗

修改后参考代码:

// 全局存储所有标记实例
const allMarkers = [];

function addMarker({maps,map,position,html,image,center,allowClick,location}){
  const newHtml = `
  <div style="background-color:white;width:300px;height:250px;border-radius:8px;box-shadow:0 2px 7px 1px rgb(0 0 0 / 30%);box-sizing: border-box;overflow: hidden;padding:12px">
    ${location.name}<br>
    ${location.phone}<br>
    ${location.address}
  </div>`;
  const infowindow = new maps.InfoWindow({
    content: newHtml,
    zIndex: 2,
    maxWidth: 500,
  });

  const marker = new maps.Marker({
    map,
    position,
    icon: image,
    infowindow,
  });
  // 把新标记加入全局数组
  allMarkers.push(marker);
  
  if(allowClick){
    maps.event.addListener(marker, "click", function(arg) {
      // 遍历关闭所有已打开的信息窗
      allMarkers.forEach(item => item.infowindow.close());
      // 打开当前标记的信息窗
      infowindow.open(map, marker);
      
      if(center){
        map.setCenter(marker.getPosition());
      }
    });
  }
  
  return marker;
}

内容的提问来源于stack exchange,提问作者notElonMusk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 03:15:11