我正在尝试使用像
这样的自定义Dom元素绘制一个矩形<button id="rect">Draw</button>
这是我正在使用的脚本
var drawingStyle = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true,
draggable: true,
};
google.maps.event.addListener(rect, 'click', function() {
var drawingManager = new google.maps.drawing.DrawingManager({
drawingControlOptions: {
drawingModes: [ google.maps.drawing.OverlayType.RECTANGLE]
},
rectangleOptions: drawingStyle,
map: map
});
drawingManager.setMap(map);
});
但点击#rect
不会导致任何事件!甚至在控制台上都没有任何错误。你能告诉我我做错了吗?
谢谢
答案 0 :(得分:1)
#rect
是一个DOM对象。要使用Google Maps Javascript API v3事件侦听器在其上收听事件,请使用addDomListener方法。
<button id="rect">Draw</button>
google.maps.event.addDomListener(document.getElementById('rect'), 'click', function() {
var drawingManager = new google.maps.drawing.DrawingManager({
drawingControlOptions: {
drawingModes: [ google.maps.drawing.OverlayType.RECTANGLE]
},
rectangleOptions: drawingStyle,
map: map
});
drawingManager.setMap(map);
});
工作代码段:
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {
lat: 45,
lng: -85
},
zoom: 4
});
}
google.maps.event.addDomListener(document.getElementById('rect'), 'click', function() {
var drawingManager = new google.maps.drawing.DrawingManager({
drawingControlOptions: {
drawingModes: [google.maps.drawing.OverlayType.RECTANGLE]
},
// rectangleOptions: drawingStyle,
map: map
});
drawingManager.setMap(map);
});
google.maps.event.addDomListener(window, 'load', initialize);
&#13;
html,
body,
#map-canvas {
height: 100%;
width: 100%;
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing"></script>
<button id="rect">Draw</button>
<div id="map-canvas"></div>
&#13;