Search code examples
overlaygoogle-maps-api-3

Make custom overlay clickable (Google Maps API v3)


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.Polygon 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?


Solution

  • Update for v3: overlayLayer doesn't accept mouse events anymore. Add your overlay to overlayMouseTarget instead, add the listener, and it should receive mouse events normally.

    //add element to clickable layer 
    this.getPanes().overlayMouseTarget.appendChild(div);
    
    // set this as locally scoped var so event does not get confused
    var me = this;
    
    // 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(me, 'click');
    });
    

    See: http://code.google.com/apis/maps/documentation/javascript/reference.html#MapPanes