Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZoomToExtent OpenLayers 3

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

like image 227
Tyler DeWitt Avatar asked May 15 '14 15:05

Tyler DeWitt


3 Answers

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()); 
like image 59
Tyler DeWitt Avatar answered Oct 20 '22 04:10

Tyler DeWitt


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.

like image 35
Naderio Avatar answered Oct 20 '22 02:10

Naderio


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.

like image 1
juminet Avatar answered Oct 20 '22 03:10

juminet