1
votes

I use openlayers 6 in my project. Layers on the map hide/show acording to zoom level.

Here is map and view defenitions:

view = new View({
    center: mapCenter,
    projection: israeliTM.getCode(),
    zoom: 0,
    resolutions: resolutions // resolutions array 
});

map = new Map({
    layers: layers,
    target: 'map',
    view: view
});

This row is fired when zoom is changed:

var curRes = map.getView().getResolution()[map.getView().getZoom()];

As you can see on view defenition resolutions defined as array and when zoom is changed I expect to get from this map.getView().getZoom() integer number that displays index in resolutions array and return current resolution. In general it works as expected but sometimes map.getView().getZoom() returns decimal number like 3.56989.

Any idea why map.getView().getZoom() returns some time decimal?

2

2 Answers

4
votes

If you are using OpenLayers 6 specify constrainResolution in the view options

view = new View({
    center: mapCenter,
    projection: israeliTM.getCode(),
    zoom: 0,
    constrainResolution: true,
    resolutions: resolutions // resolutions array 
});

and for OpenLayers 5 specify constrainResolution in the interaction options

map = new Map({
    layers: layers,
    target: 'map',
    interactions: defaultInteractions({
        constrainResolution: true
    }),
    view: view
});
2
votes

This is expected behavior and it actually returns a Number() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number

This change seems to have appeared with the gl version as you now don't have defined zoom levels.

Interesting to note is that whenever the map zoom control (+ -) UI buttons are used, the value appears to always increase/decrease to the next whole number integer (e.g. 3.462 would become 3.0 or 4.0) but when a pinch-to-zoom event occurs, the values generally contain a decimal portion.

If you want it to be whole number step based then check out:

https://github.com/mapbox/mapbox-gl-js/pull/7863

specifically:

https://github.com/mapbox/mapbox-gl-js/pull/7863/commits/19b164205208e99bbbd62750cfb7e845819ab8e4