views:

627

answers:

1

I have a custom overlay class (ImageOverlay) which inherits from google.maps.OverlayView. I want it to respond to Google Maps click events (not just DOM click events) but simply using addListener doesn't seem to do the trick.

e.g. I have a shapes array which contains a mixture of google.maps.Polgon and ImageOverlay objects:

for (var i in shapes) {
  google.maps.event.addListener(shapes[i], 'click', function(){alert('hi')});
}

Clicking on the polygons triggers an alert but clicking on the custom overlays does nothing.

How do I make Google Maps API treat the overlays as clickable?

A: 

The Maps API can't automatically determine which portions of your overlay should be clickable (i.e. if you render an image with a transparent background, if would be up to your overlay class to determine whether clicks in the transparent region count as valid clicks or not).

You should add DOM listeners to the overlays you draw, and then trigger your own Maps API click event if this is a valid click.

Example:

FooBar.prototype.onAdd = function() {
  // Create a div and append it to a map pane. 
  var div = document.createElement('div');
  div.style = "height: 100px; width: 100px";
  this.getPanes().overlayLayer.appendChild(div);

  // Add a listener - we'll accept clicks anywhere on this div, but you may want
  // to validate the click i.e. verify it occurred in some portion of your overlay.
  google.maps.event.addDomListener(div, 'click', function() {
    google.maps.event.trigger(this, 'click');
  });

  // Position your overlay etc.
}
</code>
plexer
Sweet.Actually that recursively triggers clicks on the div so you need to trigger the second click on the overlay itself:var that = this;google.maps.event.addDomListener(this.div, 'click', function() { google.maps.event.trigger(that, 'click');});
Tamlyn
Ah yes, I closure'd myself. I intended that internal this to be a reference to this in the outer scope :) Thanks
plexer