Leaflet TimeDimension Plugin – Moving Leaflet.TimeDimension Plugin Slider with Keyboard

leafletleaflet-plugins

I added a time dimension slider to a leaflet map to display a series of points in a range of time. This is the code:

     var mymap = L.map('mapid', {
        zoom: 3,
        center: [50.4, 10.7],
        keyboard: false,
        timeDimension: true,
        timeDimensionOptions: {
          timeInterval:  startDate + "/" + endDate ,
          period: "P30D"
        },
      });  


      var timeDimension = mymap.timeDimension;
      var player        = new L.TimeDimension.Player({
        transitionTime: 100,
        loop: false,
        startOver:true
      }, timeDimension);
    
      var timeDimensionControlOptions = {
          player:        player,
          timeDimension: timeDimension,
          position:      'bottomleft',
          autoPlay:      false,
          minSpeed:      1,
          speedStep:     0.5,
          maxSpeed:      15,
          timeSliderDragUpdate: true
      };
    
      var timeDimensionControl = new L.Control.TimeDimension(timeDimensionControlOptions);
      mymap.addControl(timeDimensionControl);
    
      L.timeDimension.layer.geoJson(myjsonlayer,{
          updateTimeDimension: true,
          addlastPoint: true,
          waitForReady: true
      }).addTo(mymap);

I would like to move the sliderbar cursor also with keyboard arrow keys as well as mouse or play button.
Is there a way to do this?
This is an example of my map.
enter image description here

Best Answer

Since Leaflet.TimeDimension plugin has no native keyboard support, you have to catch keyboard events with standard keydown event listener and then use plugin .nextTime and .previousTime methods to move the slider.

Code for this could look something like this:

function handleKeyDown(evt) {
  if (evt.keyCode == 39)
    timeDimension.nextTime(1);
  else if (evt.keyCode == 37) {
    timeDimension.previousTime(1);
  }
}

document.addEventListener('keydown', handleKeyDown);