9

I want to zoom on the extent of all the features contained in a list.

Firstly, I put my feature in a list:

selectedFeatures = [];    
vector2.getSource().forEachFeature(function(feature) {
                var att = feature.get("NOM");
                if (att == strUser) {
                    selectedFeatures.push(feature);
                    }
                });

Secondly, here my problem... i want to zoom on the extent of all the feature on my list "selectedFeatures"

I try this but always return me an infinite extent:

var vectorSource = new ol.source.Vector({
        projection: 'EPSG:3857',
        features: selectedFeatures //add an array of features
        });

var dataExtent = vectorSource.getExtent();
map.getView().fitExtent(dataExtent, map.getSize())
console.log("Extents : " + dataExtent);

Someone have a solution to get the extent of features contained in a list ?

FatAl
  • 859
  • 1
  • 6
  • 20
  • 1
    Actually `vectorSource.getExtent()` should work fine. Might there be a problem with the coordinates of your features? – tsauerwein May 04 '15 at 07:40
  • There is something wrong with my selectedFeatures. I'M able to get the extent of each feature but once i put them on my list "selectedFeatures" I have problem to get information on this feature. May be I do something wrong when I add feature on a new Vector Source ?? (My data is a GeoJSON format) – FatAl May 04 '15 at 14:36
  • Maybe you could create a JSFiddle with a handful of features that you have this problem with? – tsauerwein May 05 '15 at 07:17
  • Knowing what version of OpenLayers 3 you are using may be useful as well. – erilem May 05 '15 at 07:31
  • I have the version 3.4.0 and i will look for a JSFiddle, I never played with it – FatAl May 05 '15 at 13:19

2 Answers2

12

This should do the trick?

var extent = features[0].getGeometry().getExtent().slice(0);
features.forEach(function(feature){ ol.extent.extend(extent,feature.getGeometry().getExtent())});
Poul K. Sørensen
  • 16,950
  • 21
  • 126
  • 283
0

There is boundingExtent function created for this need:

const selectedFeatures = vector2.getSource().getFeatures()
  .filter((feature) => feature.get('NOM') == strUser)

const bounds = ol.extent.boundingExtent(selectedFeatures)

map.getView().fit(bounds)

I haven't actually tested the code, but you get the idea.