How to catch ctrl+click on the map ?

303 views
Skip to first unread message

Pascal Boulesteix

unread,
Sep 19, 2023, 3:40:30 AM9/19/23
to Leaflet
Hi

Currently, I intercept single clicks with
map.on('click', function(ev) {.....} );

I would like to know if the ctrl key is pressed during a click.

How to do ?

Edwin Corrigan

unread,
Sep 19, 2023, 9:09:03 AM9/19/23
to leafl...@googlegroups.com
Hi Pascal, 

Someone may have a more 'Leaflet' way to do this, or even a better suggestion. But creating keyup and keydown event listeners should work for this. Something like:

let isControlPressed = false;
const keyDownHandler = (event) => {
  if (event.key === 'Control') {
    isControlPressed = true;
  }
}

const keyUpHandler = (event) => {
  if (event.key === 'Control') {
    isControlPressed = false;
  }
}

window.addEventListener('keydown', keyDownHandler);
window.addEventListener('keyup', keyUpHandler);

map.on('click', function(ev) {
  if (isControlPressed) {
    // do what you want when ctrl is pressed and map is clicked
  }
});

// inside a destroy function
window.removeEventListener('keydown', keyDownHandler);
window.removeEventListener('keyup', keyUpHandler);

--

---
You received this message because you are subscribed to the Google Groups "Leaflet" group.
To unsubscribe from this group and stop receiving emails from it, send an email to leaflet-js+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/leaflet-js/01715570-4175-4f78-a833-45ca3d20f167n%40googlegroups.com.

Pascal Boulesteix

unread,
Sep 19, 2023, 9:58:22 AM9/19/23
to Leaflet
The code below seem to work fine !

map.on('click', function(ev){
    isCtrlKey=ev.originalEvent.ctrlKey;
    ismetaKey=ev.originalEvent.metaKey;
    if (isCtrlKey || ismetaKey) {
            alert("CTRL ");
        }
        else
        {
             alert("PAS CTRL");
Reply all
Reply to author
Forward
0 new messages