Android中如何为Google Map信息窗口添加带独立点击监听器的双按钮?
Google Maps信息窗口按钮点击事件失效的解决方案
因为Google Maps信息窗口的DOM会在每次打开时重新渲染,直接提前绑定的事件会失效,推荐两种可行方案:
方案一:监听信息窗口的domready事件
当信息窗口的DOM完全加载完成后,再给按钮绑定点击事件,示例代码:
// 创建标记 const marker = new google.maps.Marker({ position: { lat: 你的纬度, lng: 你的经度 }, map: map }); // 信息窗口内容,包含两个按钮 const infoWindowContent = ` <div> <button id="btn1">按钮1</button> <button id="btn2">按钮2</button> </div> `; const infoWindow = new google.maps.InfoWindow({ content: infoWindowContent }); // 绑定标记点击事件打开信息窗口 marker.addListener('click', () => { infoWindow.open(map, marker); }); // 监听信息窗口的domready事件,此时DOM已加载完成 infoWindow.addListener('domready', () => { document.getElementById('btn1').addEventListener('click', () => { console.log('按钮1被点击'); // 执行你的逻辑 }); document.getElementById('btn2').addEventListener('click', () => { console.log('按钮2被点击'); // 执行你的逻辑 }); });
方案二:使用事件委托
把点击事件绑定到地图的父容器(或者页面的body),通过判断目标元素的标识(比如id、类名)来触发对应逻辑,避免DOM重新渲染导致的事件丢失:
// 提前给容器绑定事件委托,比如绑定到body document.body.addEventListener('click', (e) => { if (e.target.id === 'btn1') { console.log('按钮1被点击'); // 执行你的逻辑 } else if (e.target.id === 'btn2') { console.log('按钮2被点击'); // 执行你的逻辑 } }); // 创建标记和信息窗口的代码和之前一致 const marker = new google.maps.Marker({ position: { lat: 你的纬度, lng: 你的经度 }, map: map }); const infoWindowContent = ` <div> <button id="btn1">按钮1</button> <button id="btn2">按钮2</button> </div> `; const infoWindow = new google.maps.InfoWindow({ content: infoWindowContent }); marker.addListener('click', () => { infoWindow.open(map, marker); });
注意:如果页面中有多个信息窗口,建议给按钮添加唯一标识(比如标记的ID作为按钮类名的一部分),避免点击逻辑冲突。
内容的提问来源于stack exchange,提问作者shahrooz nld
相关产品推荐
相关产品推荐

