11

Is there a way to dynamically set the zoom level so that the current layers always fit within the width of the map frame on page load?

Currently the zoom level is set statically such that when using a full resolution monitor the application loads perfectly the entirety of the map fits but when loading the map at a lower resolution the map loads at the same zoom level but features are cut off.

3 Answers 3

17

According to this answer at StackOverflow, the functions have been renamed in OpenLayers 3.7 and later.

This is what works for me in OpenLayers 3.15.1:

var extent = my_vector_layer.getSource().getExtent();
map.getView().fit(extent, map.getSize());
1
  • my_vector_layer.getSource().getExtent() will return infinity if the layer is not visible , means we have set some max resolution for that vector layer when adding on to the map . any solution ? Commented Sep 6, 2018 at 11:48
7

The Dirk's works fine, but be carefull, if you have only one feature in your layer, it will zoom in way too much.

you can use

var extent = my_vector_layer.getSource().getExtent();
map.getView().fit(extent, {size:map.getSize(), maxZoom:16})

to have a reasonable max zoom level

4

You can adjust the map's view to fit an extent with: http://openlayers.org/en/v3.6.0/apidoc/ol.View.html#fitExtent

Use getExtent() to retrieve your layers' extent: e.g. http://openlayers.org/en/v3.6.0/apidoc/ol.source.Vector.html#getExtent

See Tim's answer at https://stackoverflow.com/questions/30121024/openlayers-3-zoom-to-combined-extent

1
  • my_vector_layer.getSource().getExtent() will return infinity if the layer is not visible , means we have set some max resolution for that vector layer when adding on to the map . any solution ? Commented Sep 6, 2018 at 11:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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