Monday, February 6, 2023

Prevent scroll position of window when focus on LeafLet Map - Mouse wheel zoom on leaflet map only after click - Leaflet map scrolls top on focus on Browsers

I have a leaflet map on an HTML page. When the map is focused the map jumps so that it's completely visible in the viewport. If the whole map doesn't fit, then the top of the map becomes aligned with the top of the viewport and the bottom just hangs off the end.
This is annoying, because then the whole page area jumped to top.
We need to add the listener immediately after the map initialized. So the whole thing becomes normal as we want like no scroll on focus.
const map = L.map('leaflet-js-map').setView([latLng[0].Longitude, latLng[0].Latitude], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    minZoom: 10,
    maxZoom: 18,
    attribution: 'Map data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors'
}).addTo(map);

map.once('focus', function(e) {
    console.log(e);
    if (map.scrollWheelZoom.enabled()) {
        map.scrollWheelZoom.disable();
    }
    else {
        map.scrollWheelZoom.enable();
    }
});

No comments:

Post a Comment