ZoomToExtent OpenLayers 3
Asked Answered
U

3

22

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".

Umbrageous answered 15/5, 2014 at 15:14 Comment(2)
have you tried ol3js.org/en/master/apidoc/ol.control.ZoomToExtent.htmlFariss
@Fariss 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.Umbrageous
U
51

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()); 
Umbrageous answered 16/5, 2014 at 20:43 Comment(6)
thanks for the credit @tylerdewitt. I was too slow to respond, so I'll give you some internet points instead. :)Fariss
View's fitExtent() seems to be deprecated in 3.4Mistymisunderstand
It is replaced with ol.View.fit in 3.7.Rabbet
map.getSize() is optional, it's the default value.Bimah
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)Peeved
@Peeved know this is old but you'll probably need view.animate() with example at openlayers.org/en/latest/examples/animation.html and docs at openlayers.org/en/latest/apidoc/…Coinstantaneous
W
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.

Wrongly answered 2/2, 2018 at 14:54 Comment(0)
S
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.

Snaggletooth answered 12/10, 2018 at 8:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.