JYP18
JYP18

Reputation: 51

Mapbox-GL: zoom scope control

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.

Upvotes: 3

Views: 890

Answers (2)

derFrosty
derFrosty

Reputation: 548

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

Upvotes: 2

tristen
tristen

Reputation: 4735

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.

Upvotes: 3

Related Questions