[GIS] Min/Max zoom levels for a TileLayer

openlayers

I create my openlayers map like this:

tmpLayer = new ol.layer.Tile({
        source: new ol.source.XYZ({
            url: my_tile_url,
            crossOrigin: 'anonymous',
        })
});

The webmap I want to include only supports zoom levels 8-15. I want the map to disappear when the current zoom is not within that range.

I could find an example in the openlayers documentation where this is achieved with min/maxResolution. Is this also possible with specifying zoom levels?

To clarify, I do not want to constrain the zoom levels (like here), I want the map to disappear outside that range like in the above example.

Best Answer

According to the openlayers documentation, ol.source.XYZ has a minZoom and maxZoom parameter. However these do not show the desired effect. They do limit the zoom level, to the specified range, however the tiles do not disappear when out of this range.

I found the following workaround, using the change:resolution event listener:

tmpLayer = new ol.layer.Tile({
    source: new ol.source.XYZ({
        url: my_tile_url,
        crossOrigin: 'anonymous',
        minZoom: 8,
        maxZoom: 15
    })
});

map.getView().on('change:resolution', function() {
    layers = map.getLayers();
    layers.forEach(function(layer, i, a) {
        tmpSource = layer.getSource()
        // 'duck typing' for source object, vector layers don't have a zoom level.
        if(typeof tmpSource.getTileGrid === 'function') {
            if(map.getView().getZoom() > tmpSource.getTileGrid().maxZoom ||
                map.getView().getZoom() < tmpSource.getTileGrid().minZoom) {
                layer.setVisible(false);
            } else {
                layer.setVisible(true);
            }
        }
    });
});
Related Question