Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenLayers 3 Extent of all features on a vector layer?

Tags:

I have an OpenLayers 3 map with a base layer and a vector layer.

this.topoLayer = new ol.layer.Vector({   source: new ol.source.Vector(),   style: style });  var baseLayer = new ol.layer.Tile({     source: new ol.source.XYZ({         url: 'http://[…]/{z}/{x}/{y}.png',         crossOrigin: 'null'     }) });  this.map = new ol.Map({     target: 'map',     layers: [baseLayer, this.topoLayer],     view: new ol.View2D({         center: ol.proj.transform([11.38,  48.54], this.options.markerEPSG, this.options.mapEPSG),         zoom: 5,     }), }); 

Upon user interaction, I add and remove several features to the vector layer. Here is the function that adds a new feature:

  var feature = new ol.Feature({         topo: topo,         selected: false,         geometry: new ol.geom.Point(ol.proj.transform(location, this.options.markerEPSG, this.options.mapEPSG)),   });    this.topoLayer.getSource().addFeatures([feature]); 

After adding/removing a new feature I would like to automatically zoom and pan the map to fit my features. In the old OpenLayers API there was the getDataExtent function on vector layers to retrieve a "bounding box" around all features shown. But I wonder how to do this with the new API.

like image 522
SomeBdyElse Avatar asked Dec 28 '13 16:12

SomeBdyElse


2 Answers

In version 3.7, ol.View.fitExtent() and ol.View.fitGeometry() have been unified in a single function: fit.

So now the code is:

 var extent = myLayer.getSource().getExtent();  map.getView().fit(extent, map.getSize()); 
like image 112
Mister Smith Avatar answered Sep 20 '22 20:09

Mister Smith


Based on Tyler DeWitt's answer you should be able to do something like this:

var view = yourmap.getView(); var view2D = view.getView2D(); var extent = yourlayer.getSource().getExtent();  view2D.fitExtent(extent, yourmap.getSize()); 

Edit: Like Tim and Stuart said the above doesn't work anymore. The following should do the trick instead:

 var extent = yourlayer.getSource().getExtent();  map.getView().fitExtent(extent, map.getSize()); 
like image 36
Danny Hoek Avatar answered Sep 23 '22 20:09

Danny Hoek