OpenLayers 3 get extent of all feature contents in a list
Asked Answered
J

2

10

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 ?

Jute answered 3/5, 2015 at 20:5 Comment(5)
Actually vectorSource.getExtent() should work fine. Might there be a problem with the coordinates of your features?Barragan
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)Jute
Maybe you could create a JSFiddle with a handful of features that you have this problem with?Barragan
Knowing what version of OpenLayers 3 you are using may be useful as well.Condiment
I have the version 3.4.0 and i will look for a JSFiddle, I never played with itJute
M
14

This should do the trick?

var extent = features[0].getGeometry().getExtent().slice(0);
features.forEach(function(feature){ ol.extent.extend(extent,feature.getGeometry().getExtent())});
Morley answered 3/5, 2015 at 23:14 Comment(3)
May be updated to use a for loop that skip the first element in the iteration stepEstebanesteem
"Features" = my list of feature (selectedFeatures)? If it's the case, it didn't work at your first line. It's telling me getExtent() is not a function.Jute
Sorry, was a bit too quick on copy pasting. Remember to do checks that features has more than 0 element and such.Estebanesteem
O
1

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.

Octad answered 14/8, 2023 at 14:6 Comment(1)
boundingExtent is taking an array of coordinates as parameter : openlayers.org/en/latest/apidoc/…Orpiment

© 2022 - 2024 — McMap. All rights reserved.