Hari Chaudhary Hari Chaudhary - 3 months ago 34
jQuery Question

How to distinguish between left and right mouse click on mousedown event in Google Map API v3

The mousedown event of Google Map API v3 gets fired on left and right click both, how can I identify whether it is right click or left click.

I am new to Google Map API, I was using Virtual Earth API until now, where I was able to distinguish between left and right mouse click on mouse down like e.leftMouseButton returns true if it is left click.

Answer

Instead of mousedown use simply click.

For right click event you can catch rightclick event this way:

google.maps.event.addListener(map, "rightclick", function(event) {
  /* do something on right click */
});

JSFIDDLE


To distinguish what button was pressed using mousedown event you can use event.which parameter. But for that, the handler should be added to DOM element (canvas), since Google API doesn't provide which option in event object.

var c = document.getElementById('map-canvas');
google.maps.event.addDomListener(c, "mousedown", function (e) {
    if (e.which === 1) {
        $("#click").text("Left click");
    } else if (e.which === 2) {
        $("#click").text("Middle click");
    } else if (e.which === 3) {
        $("#click").text("Right click");
    }
});

JSFIDDLE