Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hooking into mousewheel event in Google Map API

Is is possible to hook into a mousewheel event in Google Map API? Without going into specifics, I need the mousewheel to zoom like it normally does in Google Map, but I also need to attach to the mousewheel event for another purpose.

But whenever I set scrollwheel to true in MapOptions, Google Map API eats up all mousewheel event and refuses to share them (very egocentric dont you think?)!

Listening to Google Map event like zoom_changed wont work, since they don't fire if map is at min or max zoom level, which is something I need. More specifically, I need to know if user tried to zoom closer when already at max-zoom level.

This "feels" solveable, but my gut feeling isnt always spot on :-)

Any ideas?

like image 322
Magnus Avatar asked Sep 17 '13 20:09

Magnus


1 Answers

You can do this by using an ordinary DOM event listener. The only trick is that you have to use a capturing event listener so you get to see the event before the Maps API does. That's because the Maps API appears to call event.stopPropagation(), so an ordinary event listener won't see the event. By using a capturing listener you see it first.

Here's an example, assuming you have a #map_canvas DIV for the map and a #log DIV for an event log:

function initialize() {
    var $map = $('#map_canvas');
    var latLng = new google.maps.LatLng( 40.708762, -74.006731 );

    var map = new google.maps.Map( $map[0], {
        zoom: 15,
        center: latLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    function wheelEvent( event ) {
        $('#log').append( '<div>wheel!</div>' );
    }

    $map[0].addEventListener( 'mousewheel', wheelEvent, true );
    $map[0].addEventListener( 'DOMMouseScroll', wheelEvent, true );
};

$( initialize );

Note that the code listens for both the DOMMouseScroll event for Firefox and the mousewheel event for other browsers. You will need to take care of the differences in the event object for these two events.

Here's the fiddle.

like image 194
Michael Geary Avatar answered Sep 21 '22 02:09

Michael Geary