TransWikia.com

Leaflet on mouse wheel event change zoom by delta

Geographic Information Systems Asked by myFirstStackOverflowQuestion on May 26, 2021

I am trying to find a way to change zoom by delta when using mouse wheel event (scroll) in Leaflet.

E.g. current map zoom is on 0 and if “scrolled” into map, zoom should be 5.

Also, zoom change should take zoom location in account.

E.g. map is 1000px * 1000px, then if mouse wheel is done on [x:1000, y:0], then it should be zoomed in that part (in right upper corner) and not random or in center.

Attempts / Results

  • adding mousewheel listener on map div – zoom delta working by calling zoomIn(), zoom position random, can not get info on coordinates since it is not Leaflet event
  • adding mousewheel listener on tile div – not able to do anything with it
  • adding zoomstart listener on map – not able to do anything with it

2 Answers

Use the zoomDelta map option to control how many zoom levels the map shall change when using keyboard controls or the zoom buttons, and the wheelPxPerZoomLevel option to control how fast the mouse wheel will change zoom levels.

Please note that scroll events are finicky, and depend on the web browser and your actual hardware. Some mice scroll in steps, some touchpads report a fine amount of scrolled pixels, some other are just weird. Assume that a "scroll click" is 60 pixels, and adjust the value of wheelPxPerZoomLevel accordingly - e.g. if you want to scroll 5 zoom levels at a time, use a value of (60/5)=12, and a zoomDelta of 5:

var map = L.map('map-container', {
    zoomDelta: 5,
    wheelPxPerZoomLevel: 12 
});

Correct answer by IvanSanchez on May 26, 2021

In addition to @IvanSanchez's answer, Leaflet from 1.0.0 onwards introduced the concept of fractional zoom levels, so you can zoom in a more controlled way. So you can use, for example,

var map = L.map('map-container', {
    zoomSnap: 0.25,
    zoomDelta: 1,
    wheelPxPerZoomLevel: 60
});

Answered by simonalexander2005 on May 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP