问题
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.
回答1:
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
回答2:
It's a long time after the question was raised, but I've just been working on a tool for a Google maps application where I wanted to initiate a process on right-mouse down, continue the process while dragging, and then end the process on right-mouse up.
So, I eventually got the right-mouse down event by using a DOM listener on the map canvas to store which button had been pressed to a global variable, and using an ordinary Google maps listener on the map object to fire another function, but with a short timer to ensure the DOM listener had properly written to the global. Something like:
var cvs = document.getElementById("map_canvas");
google.maps.event.addDomListener(cvs, 'mousedown', function(event) { getMouseBtnFromDomListener(event); });
google.maps.event.addListener(mainMap, 'mousedown', function(event) { setTimeout(function() { initFooEvent(event); },30); });
function getMouseBtnFromDomListener(evt) {
// 1=left, 2=middle (not recognized with my mouse), 3=right...
mButton = evt.which; // global var
}
Works well enough for me...
回答3:
try this
var _key = (window.Event) ? e.which : e.keyCode;
example:
var c = document.getElementById('map-canvas');
google.maps.event.addDomListener(c, "mousedown", function (e) {
var _key = (window.Event) ? e.which : e.keyCode;
if (_key === 1) {
$("#click").text("Left click");
} else if (_key === 2) {
$("#click").text("Middle click");
} else if (_key === 3) {
$("#click").text("Right click");
}
});
来源:https://stackoverflow.com/questions/26397686/how-to-distinguish-between-left-and-right-mouse-click-on-mousedown-event-in-goog