2

I am using OpenLayers 3 to display a single image. I am trying to write a function that will zoom so the left side of the image touches to the left side of the container and the right side of the image touches the right side of the container. It doesn't matter if the top and bottom of the image is outside the view.

I have set the projection extent to be the same as the image resolution:

var extent = [0, 0, 2480, 3508];
projection = new ol.proj.Projection({
    code: 'image',
    units: 'pixels',
    extent: extent
});

I was experimenting with the fitExtent function in the console window using the code:

map.getView().fitExtent([0,0,2480,3508],map.getSize())

The result I got wasn't quite what I was expecting. The image is centred, but appears much smaller than I was expecting. I was expecting at least the top and bottom of the image to be touching the top and bottom of the container.

An explanation of why this is happening would be fantastic. A solution that fits the image so the left is on the left and the right is on the right (a zoomToExtentY function) would be even better.

Example fiddle...

Jose Gómez
  • 2,891
  • 2
  • 28
  • 52
SausageFingers
  • 1,726
  • 5
  • 29
  • 50
  • 2
    This has to do with constrained resolution. In my case I solved it by making sure the resolution you want to achieve is part of the resolutions array of the view. I actually set minResolution and maxResolution to the same value since I was just interested in a single resolution (no interactions on that map): https://github.com/geoext/geoext3/blob/master/src/component/FeatureRenderer.js#L249:L255 – bartvde Jun 22 '15 at 06:35
  • I did upvote your comment @bartvde but then accidentally undid it. Now SO wont allow me to re-upvote it. Apologies. – SausageFingers Jun 22 '15 at 15:14
  • 1
    No problem, glad it helped you. – bartvde Jun 22 '15 at 18:52

1 Answers1

1

Thanks to the comment from @bartvde I was able to make the fitExtent() work how I expected by first calculating the the resolution of the longest axis:

    var imgW = extent[2];
    var imgH = extent[3];
    var boxW = document.getElementById('map').offsetWidth;
    var boxH = document.getElementById('map').offsetHeight;

    var xRes = imgW / boxW;
    var yRes = imgH / boxH;
    var maxRes = xRes < yRes ? yRes : xRes;

Then setting the maxResolution of the default map view:

view: new ol.View({
    projection: projection,
    center: ol.extent.getCenter(extent),
    zoom: 0,
    maxResolution:maxRes
})

My other requirement of setting the zoom level so the left and right of the image touched the left and right of the container was solved by setting the resolution of the view to that of the x Axis:

    //set the resolution to that of the xAxis.
    map.getView().setResolution(xRes);

See this fiddle for example of both the above settings in action.

SausageFingers
  • 1,726
  • 5
  • 29
  • 50