Get extent on all layers in Openalyers 5

1k Views Asked by At

I'm trying to do quite a trivial activity: fit a map to the extent of all layers.

But I'm stuck:

Here is my code:

import { createEmpty, getWidth, getHeight, extend } from 'ol/extent.js';

    function centraTuttiLayer(map)
    {
      var extent = createEmpty();
      //modifico l'estensione del layer per contenere tutto
      map.getLayers().forEach(function(l) {    
          extend(extent, l.getExtent());
      });
      map.getView().fit(extent);
    }

I alway get getExtent() as empty. I've also tried l.getSource() and then getExtent(), but with no luck. What am I doing wrong?

Thanks Massimo

1

There are 1 best solutions below

0
On

You can`t get extent of layer. Do it with source

map.getLayers().forEach(function(l) {
    let source = l.getSource();
    if(!(source instanceof OSM)){
        extend(extent, source.getExtent());
    }
});
map.getView().fit(extent,{
    maxZoom: 15,
    padding: [50,50,50,50]
});