21

OpenLayers 2 had a very useful map.zoomToExtent(extent) feature. Is there something similar in OpenLayers 3? I can get the extent of interest with source.getExtent(), but I can't figure out how to apply that extent as a "zoom level".

Tyler DeWitt
  • 22,191
  • 36
  • 108
  • 189
  • 1
    have you tried http://ol3js.org/en/master/apidoc/ol.control.ZoomToExtent.html – sfletche May 15 '14 at 18:59
  • @sfletche That turned out to be the right answer. If you want to change your comment to an answer I'll select it so you can get awesome internet points. – Tyler DeWitt May 16 '14 at 13:21

3 Answers3

49

Going off the function sfletche linked to:

var extent = source.getExtent();
map.getView().fitExtent(extent, map.getSize());

EDIT July 23, 2013

Apparently fitExtent is deprecated. Should be ol.View.fit, so something linke this (untestesd):

var extent = source.getExtent();
map.getView().fit(extent, map.getSize()); 
Tyler DeWitt
  • 22,191
  • 36
  • 108
  • 189
  • thanks for the credit @tylerdewitt. I was too slow to respond, so I'll give you some internet points instead. :) – sfletche May 17 '14 at 04:31
  • View's fitExtent() seems to be deprecated in 3.4 – user1702401 Apr 14 '15 at 21:08
  • 3
    It is replaced with [`ol.View.fit`](http://openlayers.org/en/v3.7.0/apidoc/ol.View.html#fit) in 3.7. – 0xcaff Jul 22 '15 at 21:36
  • 1
    map.getSize() is optional, it's the default value. – Toilal Jun 15 '17 at 14:26
  • Hi there. I am trying with `this.olmap.getView().fit(ext, size, [0, 0, 0, 0], true, false, 0, 15, 2000); ` to make the zoom smooth and animated. And its still not smooth or animated. Any ideas? Thanks (this is OL5) – slevin Aug 04 '18 at 11:59
  • @slevin know this is old but you'll probably need view.animate() with example at https://openlayers.org/en/latest/examples/animation.html and docs at https://openlayers.org/en/latest/apidoc/module-ol_View-View.html#animate – Andrew T Feb 08 '19 at 17:15
4

With OpenLayers 4.x this is still a valid solution:

map.getView().fit(source.getExtent(), map.getSize()); 

Make sure to set the optional second parameter to prevent console errors, if there are no points on the map.

Naderio
  • 1,052
  • 7
  • 19
1

With OpenLayers 4.x, I found the following methods useful:

map.getView().setCenter([x, y]); map.getView().setZoom(z);

where x, y, z are the coordinates where you want to zoom to.

juminet
  • 297
  • 1
  • 3
  • 11