事件在谷歌地图V3上点击矩形

时间:2014-03-09 16:22:09

标签: jquery google-maps events google-maps-api-3 click

我有一个地图,用户可以绘制一些矩形,用户绘制所有矩形后,他们可以点击他们开始一些事件,如显示更多信息,调用Web服务,更改矩形的属性和更多。

我需要为每个矩形添加一个点击事件监听器,我尝试了以下代码,但它不起作用。我也试过this solution

function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(10.066611095611856,-69.33721108996582),
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.HYBRID,
    };
    var map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);


var drawingManager = new google.maps.drawing.DrawingManager({
      drawingControl: true,
      drawingControlOptions: {
        position: google.maps.ControlPosition.TOP_CENTER,
        drawingModes: [google.maps.drawing.OverlayType.RECTANGLE]
      },
      rectangleOptions: {
          fillColor: '#0011aa',
          fillOpacity: 1,
          strokeWeight: 5,
          clickable: false,
          editable: true,
          zIndex: 1
        }
});

drawingManager.setMap(map);

google.maps.event.addListener(drawingManager, 'rectanglecomplete', function(rectangle) {
        /* DOES NOT WORK */
        google.maps.event.addListener(rectangle, 'click', function() {
            console.log(rectangle);
        });
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

先谢谢。

1 个答案:

答案 0 :(得分:5)

两件事。首先,您需要使您的矩形可以点击。

  var drawingManager = new google.maps.drawing.DrawingManager({
      drawingControl: true,
      drawingControlOptions: {
        position: google.maps.ControlPosition.TOP_CENTER,
        drawingModes: [google.maps.drawing.OverlayType.RECTANGLE]
      },
      rectangleOptions: {
          fillColor: '#0011aa',
          fillOpacity: 1,
          strokeWeight: 5,
          clickable: true,
          editable: true,
          zIndex: 1
        }
});

二。绘图管理器正在绘制时,所有单击侦听器都被禁止。矩形完成后,您需要将绘图模式设置为null。

  google.maps.event.addListener(drawingManager, 'rectanglecomplete', function(rectangle) {
        drawingManager.setDrawingMode(null);
         /* DOES WORK */
        google.maps.event.addListener(rectangle, 'click', function() {
            console.log(rectangle);
        });
  });