【发布时间】:2022-08-03 20:55:50
【问题描述】:
我创建了一个带有单击事件侦听器(单击和右键单击)的多边形。在第一次单击矩形时会发出警报,但在重新创建矩形后,事件不起作用。我假设我正在用其他同名替换地图对象。不确定我做错了什么。参考我的代码 sn-p
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();
google.maps.event.addListener(rectangle, \'click\', function() {
alert(\"Clicked\");
});
google.maps.event.addListener(rectangle, \'rightclick\', function() {
alert(\"Right Clicked\");
});
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);
}
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();
});
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<html>
<head>
<title>User-Editable Shapes</title>
<script src=\"https://polyfill.io/v3/polyfill.min.js?features=default\"></script>
</head>
<body>
<script
src=\"https://maps.googleapis.com/maps/api/js?key=AIzaSyBIc-PhM9_Uwpjbks0WPvtkKYagOXTk12A&callback=initMap&\" async defer></script>
<div id=\"map\"></div>
</body>
</html>
标签: javascript google-maps google-maps-api-3