Search code examples
javascriptopenlayers

OpenLayers: lock map to the vector's extents


I'm learning how it is possible to create a library in JavaScript using OpenLayers. Normally I use the code below to lock my map on the vector extent passed manually.

var minX= 3.0025038498794938;
var minY= 47.7706339888675302;
var maxX= 5.1702255722362533;
var maxY= 49.5690401585264695;
var maxExtent = [minX, minY, maxX, maxY];
var boundary = ol.proj.transformExtent(maxExtent, 'EPSG:4326', 'EPSG:3857');
var center = ol.proj.transform([4.0863647111, 48.6698370737], 'EPSG:4326', 'EPSG:3857');

var view = new ol.View({
  extent: boundary,
  center: center,
  zoom: 9,
  maxZoom: 18,
  minZoom: 8,
});
map.setView(view);

My aim is use the same phylosophy but using the extent of a vector inside a specific function. I'm be able to load the map on a zoom on the vector extensions:

function getPolygonsExtent() {
  vectorsLayer.getSource().once('change', function(evt) {
    if (vectorsLayer.getSource().getState() === 'ready') {
      if (vectorsLayer.getSource().getFeatures().length > 0) {
        extent = vectorsLayer.getSource().getExtent();
        options = {
          size: map.getSize(),
          padding: [0, 0, 0, 0],
        }
        map.getView().fit(extent, options);
      }
    }
  });
};

But I've no idea how I can follow my aim. I thought there was a function like map.getView().setExtent(extent);, but is is not so. Any suggestions?


Solution

  • There is no setExtent() method so you will need to create a new view

      map.getView().fit(extent, options);
      var newView = new ol.View({
        extent: extent,
        showFullExtent: true,
        center: map.getView().getCenter(),
        zoom: map.getView().getZoom(),
        maxZoom: 18,
        minZoom: 8,
     });
     map.setView(newView);
    

    The fit() method fits the extent inside the map, but by default the extent option constrains the map inside the extent, use showFullExtent for similar behaviour to fit(). If your fit options include a duration you will also need a callback to update the view when it is finished inside of doing it in inline code.