如何在其创建范围之外将事件侦听器添加到自定义Google Map控件

时间:2019-04-09 07:27:23

标签: javascript google-maps google-maps-api-3

我创建了带有点击事件监听器的自定义Google Maps控件

function CenterControl(controlDiv, map, CenterPosition, DefaultZoom) {
    // Set CSS for the control border.
    var controlUI = document.createElement('div');
    controlUI.style.backgroundColor = '#fff';
    controlUI.style.border = '2px solid #fff';
    controlUI.style.borderRadius = '3px';
    controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
    controlUI.style.cursor = 'pointer';
    controlUI.style.marginBottom = '22px';
    controlUI.style.textAlign = 'center';
    controlUI.title = 'Click to recenter the map';
    controlDiv.appendChild(controlUI);
    // Set CSS for the control interior.
    var controlText = document.createElement('div');
    controlText.style.color = 'rgb(25,25,25)';
    controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
    controlText.style.fontSize = '15px';
    controlText.style.fontWeight = 'bold';
    controlText.style.lineHeight = '30px';
    controlText.style.paddingLeft = '5px';
    controlText.style.paddingRight = '5px';
    controlText.innerHTML = 'Center Map';
    controlUI.appendChild(controlText);
    controlUI.addEventListener('click', function() {
      map.setZoom(DefaultZoom);
      map.setCenter(CenterPosition);
    });
}

var centerControlDiv = document.createElement('div');
var centerControl = new CenterControl(centerControlDiv, map, DefaultCenter, DefaultZoom);
centerControlDiv.index = 1;
map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(centerControlDiv);

我想在类似这样的代码中的其他位置向此控件添加另一个click事件监听器

google.maps.event.addListener(centerControl, 'click', function () {
    console.log('sdfgsdfgdgdfg');
    if (InfoWindow) {
        InfoWindow.close();
     }
});

这根本不起作用,并且控制台日志没有显示该事件侦听器的输出。有没有一种方法而无需创建infoWindows数组吗?

0 个答案:

没有答案