获取 Google 地图 API 中的标记列表

Get list of markers in Google Maps API

我的着陆页上有 Javascript 中的地图。 我设置了几个标记,并让它们的信息 Windows 在单击时显示。

当您单击标记时,它会显示信息 window。麻烦的是没有办法关闭其他的。

我可以关闭这里曾经是一个 .markers 属性 来获取所有标记,所以我可以在 for 循环中关闭每个标记。 这不再存在。

我试过使用共享信息 window。它不起作用,因为无法在标记的单击事件中设置内容。

这看起来应该很简单。

有什么想法吗?

参考代码:

  function addMarker({maps,map,position,html,image,center,allowClick,location}){
    // Create InfoWindow
    if (infowindow) {
      infowindow.close();
  }
  const newHtml=`  <div
  style={{backgroundColor:"white",width:"300px",height:"250px",borderRadius:"8px",boxShadow:"0 2px 7px 1px rgb(0 0 0 / 30%",boxSizing: "border-box",
overflow: "hidden",padding:"12px"}}
>
  ${location.name}
  ${location.phone}
  ${location.address}
</div>`
   infowindow = new maps.InfoWindow({
      content: newHtml,
      zIndex: 2,
      maxWidth: 500,
    });
    
    // Add Marker with infowindow
    const marker = new maps.Marker({
      map,
      position,
      icon: image,
      infowindow,
    });
    
 
    if(allowClick){
      // Add Click Event to Marker
      maps.event.addListener(marker, "click", function(arg) {
        //NEED TO CLOSE OTHERS HERE!!!


        // Open Info Window
        infowindow.open(map, marker);
        
        // Center Map on Marker
        if(center){
          map.setCenter(marker.getPosition());
        }
      
      });
    }
    
    return marker;
  }

将信息窗口保存在一个变量中。每当您打开另一个标记时,它会关闭前一个标记。

const myLatLng = new google.maps.LatLng(10.795871902729937, 106.64540961817315),
    myOptions = {
        zoom: 11,
        center: myLatLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    },
    map = new google.maps.Map(document.getElementById('map-canvas'), myOptions)
let infowindow
const positions = [
  {lat: 10.876800062989094, lng: 106.73742011622002},
  {lat: 10.781684787932484, lng: 106.62806039709115},
  { lat: 10.825433659372413,lng: 106.5160903436142 }
]

const markers = positions.map(position => {
    const marker = new google.maps.Marker({
    position,
    map,
  });
  marker.setMap(map)
  
  return marker
})
// Add click event for every marker to open new infowindow
markers.forEach((marker, index) => {
    marker.addListener("click", () => {
    if(infowindow) infowindow.close() // close previous infowindow
            let content = `Marker ${index}`
    infowindow = new google.maps.InfoWindow({
      content,
    })
    infowindow.open(map, marker)
  })
})

Code example