我的著陸頁上有一張 Javascript 地圖。我設定了幾個標記,并讓它們在單擊時顯示在 Windows 中。
當您單擊標記時,它會顯示資訊視窗。問題是沒有辦法關閉其他人。
我可以 closehere 曾經是一個 .markers 屬性來獲取所有標記,這樣我就可以在 for 回圈中關閉每個標記。這已經不存在了。
我試過使用共享資訊視窗。它不起作用,因為無法在標記的點擊事件中設定內容。
這看起來應該很簡單。
有任何想法嗎?
參考代碼:
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;
}
uj5u.com熱心網友回復:
將資訊視窗保持在一個變數中。每當您打開另一個標記時,它都會關閉前一個。
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)
})
})
代碼示例
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/378568.html
