How to get the size of a GeoJSON data source?

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 a vector source:

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

Now I want to get a degree:

 var extent = vectorSource.getExtent(); 

However, the extent value is:

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

I am using OL 3.9.0, and the vector layer with this source is displayed correctly. What am I doing wrong?

+5
source share
3 answers

I get it. I need to wait for the source to load:

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

EDIT: It may be safer to scale only if the layer is not empty:

 vectorSource.once('change',function(e){ if(vectorSource.getState() === 'ready') { if(layers[0].getSource().getFeatures().length>0) { map.getView().fit(vectorSource.getExtent(), map.getSize()); } } }); 
+5
source

If you are looking for fit , try this:

 var extent = *YOURLAYER*.getSource().getExtent(); map.getView().fit(extent, map.getSize()); 
+1
source

You can use a loop for each function and create calculated boundaries as follows:

 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()); 
+1
source

All Articles