WisdomOfAPerson
WisdomOfAPerson

Reputation: 23

How to only enable map dragging in Leaflet when spacebar is held down?

The default behaviour of Leaflet maps is to drag the view around using only mouse-down. I'd like to enable dragging with the mouse only if spacebar is pressed as well. I need mouse dragging without spacebar to do something else and not drag the view. I want to select entities with it, like on windows desktop where you can select files by mouse drag.

I'd love some help on how I can achieve this behaviour :)

Upvotes: 1

Views: 1621

Answers (1)

Parn
Parn

Reputation: 918

This example will able to drag when spacebar is pressed. For dragging with mouse-only, you need to configure their library. Or write some script to modify a mouse-drag event. Hope this will help.

// Initialize leaflet map
var map = L.map('map').setView([40.7128, -74.0060], 7);
var googleTile = L.tileLayer('http://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}',{
   maxZoom: 20,
   subdomains:['mt0','mt1','mt2','mt3'],
   attribution: ''
}).addTo(map);
// Disable map dragging event (default)
map.dragging.disable();
// Keydown and keyup event
document.body.onkeydown = function(e){
    if(e.keyCode == 32){
        map.dragging.enable();
    }
}
document.body.onkeyup = function(e){
    if(e.keyCode == 32){
        map.dragging.disable();
    }
}
#map { width: 300px; height: 150px; }
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<strong>Press your 'spacebar' key to drag</strong>
<div id="map"></div>

Upvotes: 1

Related Questions