openlayers-3

Is there a 'getZoomForResolution' in OpenLayers 3?


OpenLayers 2 used to have a getZoomForResolution method that would give you the zoom level (or closest zoom level) of a given resolution.

I don't see any such method in ol3, for the ol.View object that is. Is there a way to achieve this with what ol.view currently have ?


Solution

  • This will give the next closest integer zoom for a give resolution:

    function zoomForResolution(resolution) {
        var zoom = 0;
        var r = 156543.03390625; // resolution for zoom 0
        while (resolution < r) {
            r /= 2;
            zoom++;
            if (resolution > r) {
                return zoom;
            }
        }
        return zoom; // resolution was greater than 156543.03390625 so return 0
    }
    
    zoomForResolution(40); // 12
    

    My brother suggested:

    var zoom = Math.ceil( (Math.log(resolution) - Math.log(156543.03390625) ) / Math.log(0.5))
    

    refining the logarithmic solution for browsers with Math.log2()

    var zoom = Math.log2(156543.03390625) - Math.log2(resolution);
    

    and for IE which does not have log2()

    var zoom = Math.log(156543.03390625) * Math.LOG2E  - Math.log(resolution) * Math.LOG2E;