How to limit zoom level in OpenLayers 2.x

One way of doing that (don't know if it's the only way) is by passing an array of available resolutions to the map constructor via the options parameter. Something like...

var map = new OpenLayers.Map('map', {
    resolutions: [0.02197265625, 0.0439453125, 0.17578125]
});

A way to get the resolutions you are interested in could be:

1) zoom your map to a desired zoom level (I did it via console by running map.zoomTo(x) where x is the zoom level I was interested in)

2) via the console log the map.resolution and take note of it

3) repeat for all the zoom levels you would like to include

You can find more in-depth information here.


In OlpenLayers 3 you can just initialize your view with the desired zoom constraints:

var map = new ol.Map({
    target: 'map',
    // ...
    view: new ol.View({
        maxZoom: 8,
        minZoom: 6,
        zoom: 7
    })
});

just add the following code to your script:

map.isValidZoomLevel = function(zoomLevel) {
        return ((zoomLevel != null) && (zoomLevel >= 6) && (zoomlevel <= 8));
}