user9571941
user9571941

Reputation:

How to "activate" ("select") a given Leaflet layer with the keyboard?

I have the clickety-click GUI thing to switch layers. However, I often want to quickly swap between two layers without moving the cursor or my eyes. For this reason, I want to know how to select/activate a specific layer.

I've searched and searched but find not one mention of this (as is typical whenever I have any kind of issue).

Once I know how Leaflet wants to do this (maybe something like L.switchToLayer(someLayer);), I can then figure out how to assign each layer to a button such as 1, 2, 3, 4, 5, 6, etc., although if you want to include that in your answer, I won't exactly complain!

(I never have any clue on which "category" (not tag) of this site to post stuff, but I'll try this one, I guess...)

Upvotes: 1

Views: 390

Answers (1)

Iavor
Iavor

Reputation: 2077

Here's one way of doing it:

var currentLayer;
var layers = [];

// Create your layers and push them to the layers array.

window.addEventListener("keypress", function(e) {
  var pressedKey = Number(e.key);

  // If button pressed is not a number, return.
  if (isNaN(pressedKey)) return;
  // If the pressed number is greater than the length of layers, return.
  if (pressedKey - 1 >= layers.length) return;
  // If currentLayer is set, remove it from the map.
  if (currentLayer) map.removeLayer(currentLayer);

  currentLayer = layers[pressedKey - 1];
  map.addLayer(currentLayer);
});

Here is a JSBin with a working example. To test it out, first click on the map and then press the numbers 1 and 2 on your keyboard. Let me know if you'd like me to explain any more of the code.

Upvotes: 1

Related Questions