When I was building the Youbike-Map project and I want to find a way to make a marker stationary when zooming in. This can help the user navigate the map more effectively.
Leaflet default Scroll Wheel Zoom Option
Leaflet only provides two options, “true” and “center”, in the ‘scrollWheelZoom’ setting. The options “true” is the default setting and will make the point where your mouse is on stationary; The second options is “center” this will make it zoom in to the center of the map no matter where the cursor is.
Default Option “true”
Cursor drifts away from the target marker.
Custom Scroll Wheel Zoom Options
Leaflet doesn’t provide a way to zoom in on a fixed custom position as mentioned above, we need to implement it ourself.
Take ScrollWheelZoom Handler Source Code as reference, we can modify the function “_performZoom()” which does the actual zooming. We only need to focus on the part where the if statement lives, other parts of the function do the calculation of how many it needs to zoom.
Example of Making New Options (LatLng)
This code over writes the original _performZoom() function and add one new options detecting for LatLng.
L.Map.ScrollWheelZoom.include({
_performZoom: function() {
var map = this._map,
zoom = map.getZoom(),
snap = this._map.options.zoomSnap || 0;
map._stop(); // stop panning and fly animations if any
// map the delta with a sigmoid function to -4..4 range leaning on -1..1
var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),
d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,
d4 = snap ? Math.ceil(d3 / snap) * snap : d3,
delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;
this._delta = 0;
this._startTime = null;
if (!delta) {
return;
}
// center wheel zoom (defualt option: 'center')
if (map.options.scrollWheelZoom === 'center') {
map.setZoom(zoom + delta);
// Add a case where scrollWheelZoom option is a specific LatLng.
} else if (map.options.scrollWheelZoom instanceof L.LatLng) {
map.setZoomAround(map.options.scrollWheelZoom, zoom + delta);
// Normal wheel zoom (default option: 'true')
} else {
map.setZoomAround(this._lastMousePos, zoom + delta);
}
}
});
Make Marker Stationary While Zooming
After modifying the _performZoom() function we can pass the marker’s LatLng to achieve the effect we want.
marker = L.marker(L.latLng()).addTo(map);
marker.on({
mouseover: mouseover,
mouseout: mouseout
})
function mouseover() {
// set the zoom option to marker's location when mouse is over the marker
map.options.scrollWheelZoom = marker.getLatLng();
}
function mouseout() {
// revert the setting back to normal when mouse is out
map.options.scrollWheelZoom = 'true';
}
Customize Zooming Result
Cursor will always stay on top of the marker.