How to get the extent of a GeoJSON vector source?
Asked Answered
P

3

10

I have this GeoJSON file (polygon.geojson)...

{
  "type": "Feature",
  "geometry": { "type": "Polygon", "coordinates": [ [ [73, 15], [83.0, 15], [83, 5], [73, 5], [73, 15] ] ] },
  "properties": { "name": "Foo" }
}

...and use it as vector source:

var vectorSource = new ol.source.Vector({
    url: 'polygon.geojson',
    format: new ol.format.GeoJSON(),
    projection : 'EPSG:4326',
});

Now I want to get the extent with:

var extent = vectorSource.getExtent();

The value of extent, however, is:

Array [ Infinity, Infinity, -Infinity, -Infinity ]

I'm using OL 3.9.0 and the vector layer with this source is displayed properly. What am I doing wrong?

Principle answered 15/9, 2015 at 11:49 Comment(3)
You could try to replace ol.js by ol-debug.js and step into the getExtent method to really see what's going on (using your browser Dev Tool). Maybe that could help.Thralldom
Sure you don't use the useSpatialIndex or call the method before the vector source has loaded any features?Chalaza
Maybe the data is not yet loaded when I want to calculate the extent (I noticed that the extent is set when I open the web console after the page has been loaded). How can I check if the data is ready loaded?Principle
P
11

I figured it out. I need to wait until the source is loaded:

vectorSource.once('change',function(e){
    if(vectorSource.getState() === 'ready') {
        var extent = vectorSource.getExtent();
        console.log(extent);
        map.getView().fit(extent, map.getSize());
    }
});

EDIT: It might be safer to zoom only if the layer isn't empty:

vectorSource.once('change',function(e){
    if(vectorSource.getState() === 'ready') { 
        if(layers[0].getSource().getFeatures().length>0) {
            map.getView().fit(vectorSource.getExtent(), map.getSize());
        }
    }
});
Principle answered 15/9, 2015 at 17:33 Comment(2)
Working on 3.15.1 confirmed too.Yourself
Exactly what I was looking for and still working for openlayers 6.3.1Intransigent
B
3

If you're looking to fit to the extent try this:

var extent = *YOURLAYER*.getSource().getExtent();
map.getView().fit(extent, map.getSize());
Blastula answered 15/9, 2015 at 16:44 Comment(1)
Yes, that's what I try to achieve. However, I get TypeError: Argument 2 of CanvasRenderingContext2D.putImageData is not a finite floating-point value.Principle
L
1

You could loop for each feature and create calculate bounds like this:

var bounds = ol.extent.createEmpty();
for(var i=0;i< features.length;i++){
ol.extent.extend(bounds,features[i].getGeometry().getExtent())
}

map.getView().fitExtend(bounds , map.getSize());
Lineup answered 3/12, 2015 at 7:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.