Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the extent of a GeoJSON vector 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 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?

like image 229
Mark Avatar asked Sep 15 '15 11:09

Mark


2 Answers

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());
        }
    }
});
like image 128
Mark Avatar answered Nov 08 '22 02:11

Mark


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

var extent = *YOURLAYER*.getSource().getExtent();
map.getView().fit(extent, map.getSize());
like image 2
dvmac01 Avatar answered Nov 08 '22 04:11

dvmac01