OpenLayers-3 setting zoom so layers fit in map window

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());

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


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