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

点击按钮重新创建Polygon后点击事件失效问题

问题分析与解决方案

问题根源

你只在initMap里给第一次创建的rectangle绑定了点击事件,当调用CreatePolygon重新生成矩形时,rectangle变量指向了新的对象实例,但这个新实例并没有绑定任何事件监听器,所以点击不再触发提示。

修复方案

把事件绑定逻辑移到CreatePolygon函数内部,每次创建新矩形后都重新绑定事件。这样不管重建多少次,新生成的矩形都会带有事件监听。

修改后的JavaScript代码:

var rectangle;
var map;
const bounds = {
    north: 44.599,
    south: 44.49,
    east: -78.443,
    west: -78.649,
  };
function initMap() {
 map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: 44.5452, lng: -78.5389 },
    zoom: 9,
  });
  
 CreatePolygon();
      
 const btnCtrlDiv = document.createElement("div");
 CustomButton(btnCtrlDiv, map);
 map.controls[google.maps.ControlPosition.LEFT_CENTER].push(btnCtrlDiv);
}

function CreatePolygon(){
  if(rectangle){
  rectangle.setMap(null);
  alert("recreating and click events gone.");
  }
  
  rectangle = new google.maps.Rectangle({
    bounds: bounds,
    editable: true,
    draggable: true,
  });
  rectangle.setMap(map);
  
  // 每次创建新矩形后重新绑定事件
  google.maps.event.addListener(rectangle, 'click', function() {
        alert("Clicked");
      });
  google.maps.event.addListener(rectangle, 'rightclick', function() {
        alert("Right Clicked");
      });
}

function CustomButton(controlDiv,gmap){
    const controlUIR = document.createElement("div");
    controlUIR.setAttribute("id", "btn1");
    controlUIR.style.backgroundColor = "#d6d6d6";
    controlUIR.innerHTML="Click Me";
    controlUIR.style.fontSize = "16px";
    controlUIR.style.height = '20px';
    controlUIR.style.width = '75px';
    controlUIR.style.border = "1px solid #000000";
    controlDiv.appendChild(controlUIR);
    // Setup the click event listeners
    controlUIR.addEventListener("click", () => {
      CreatePolygon();
    });
    }

额外优化建议

如果担心频繁重建矩形导致内存泄漏,可以在移除旧矩形前先清除它的所有事件监听器:

function CreatePolygon(){
  if(rectangle){
  // 清除旧矩形的所有事件监听器
  google.maps.event.clearInstanceListeners(rectangle);
  rectangle.setMap(null);
  alert("recreating and click events gone.");
  }
  
  // 后续创建和绑定事件的代码不变...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 12:33:19