0

I'm attempting to use the ol.View's extent property to ensure the user stays within the bounds of the map. The code below works for the height (vertically) but he user can still move the map outside width wise (horizontally) and see the edges:

var width = window.innerWidth;
  var height = window.innerHeight;
  var mapW = 1789;
  var mapH = 993;

  console.log(width);
  console.log(height);

  var extent = [0, 0, 1789, 993];
  var projection = new ol.proj.Projection({
    units: 'pixels',
    extent: extent
  });

  var map = new ol.Map({
    layers: [
      new ol.layer.Image({
        source: new ol.source.ImageStatic({
          url: 'assets/img/map-bigger.jpg',
          projection: projection,
          imageExtent: extent
        })
      })
    ],
    target: 'map',
    view: new ol.View({
      projection: projection,
      center: ol.extent.getCenter(extent),
      zoom: 3.5,
      maxZoom: 4.5,
      minZoom: 3,
      extent: extent
    })
  });

  map.setView(
    new ol.View({
      projection: projection,
    center: ol.extent.getCenter(extent),
    zoom: 3.5,
    maxZoom: 4.5,
    minZoom: 3,
    extent: map.getView().calculateExtent(map.getSize())  
    })
  );

If I resize the window's width to offset this gap it works as expected. However, if I reload the page after the width change the map won't drag far enough to see the full map, as it's cut off.

1

The extent property of a view constrains the view's center, it doesn't specify the extent of the viewable map. The actual coverage will depend on the map size and resolution and will change as the resolution changes. To maintain a constant coverage but you would need to recalculate the center constraint and reset the view as the resolution changes (ignoring very small changes to avoid performance issues).

var extent = map.getView().calculateExtent(); // opening coverage
var resolution = 0;

function resChange() {
    var newResolution = map.getView().getResolution();
    if (resolution == 0 || Math.abs((newResolution-resolution)/resolution) > 0.01) {
        resolution = newResolution;
        var width = map.getSize()[0] * resolution;
        var height = map.getSize()[1] * resolution;
        var view = new ol.View({
            projection: map.getView().getProjection(),
            extent: [extent[0]+(width/2), extent[1]+(height/2), extent[2]-(width/2), extent[3]-(height/2)],
            center: map.getView().getCenter(),
            resolution: resolution,
            maxZoom: map.getView().getMaxZoom(),
            minZoom: map.getView().getMinZoom()
        });
        view.on('change:resolution', resChange);
        map.setView(view);
    }
}

resChange();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.