What do you code to control the zoom scope of a custom mapbox.gl map so that when the user zooms out and in it'll always start and end, respectively, at the same longitude/latitude despite where the user's cursor/pointer is?
Right now I have a maxZoom and minZoom set but when the user zooms out and back in, it lands where the cursor is, not the map's starting point, which is where i want it zoomed back to.
Asked
Active
Viewed 629 times
2

JYP18
- 41
- 5
-
Possible duplicate of [Mapbox.GL: scroll zoom in and out to specific coordinates on custom mapbox map](http://stackoverflow.com/questions/35510270/mapbox-gl-scroll-zoom-in-and-out-to-specific-coordinates-on-custom-mapbox-map) – Lucas Wojciechowski Mar 02 '16 at 19:20
2 Answers
3
You can control the coordinates where a map can be zoomed out by setting a bounding box:
// Set bounds to New York, New York
var bounds = [
[-74.04728500751165, 40.68392799015035], // Southwest coordinates
[-73.91058699000139, 40.87764500765852] // Northeast coordinates
];
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v8',
maxBounds: bounds
});
So zooming out would always land on these coordinates. See restrict bounds for a live example.

tristen
- 4,605
- 4
- 24
- 19
-
Oh thank you Tristen, but in this example, when the user scrolls to zoom back in, how do you control it such that it zooms exactly to where you started? Is there a MinBounds option? – JYP18 Feb 17 '16 at 19:02
1
Recently I had the same problem and my solution was quite simple actually. A mix of answers that led me here.
I disabled the mapbox default scrollZoom option.
let map = new mapboxgl.Map({
container: 'map',
scrollZoom: false,
});
After that I listened to the event wheel
and set the zoom through there.
map.on('wheel', (e) => {
const { deltaY } = e.originalEvent;
const currentZoom = map.getZoom();
if (!currentZoom) return;
const newZoom = currentZoom - deltaY / 120;
// I'm dividing by 120 because all delta values are multiples of 120, making the zoom in/out "consistent"
// subtract the currentZoom by the deltaY if you want to keep mouseWheelUp as ZoomIn and mouseWheelDown as ZoomOut
map.setZoom(newZoom);
});
Note: I know I'm 7 years too late, but hey maybe I can help someone out that might have the same problem
Edit: If you are wondering why delta values are multiple of 120 check this other question here on stackoverflow

derFrosty
- 550
- 3
- 17