简体   繁体   English

如何获得GeoJSON矢量源的范围?

[英]How to get the extent of a GeoJSON vector source?

I have this GeoJSON file (polygon.geojson)... 我有这个GeoJSON文件(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: 但是, extent的值是:

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

I'm using OL 3.9.0 and the vector layer with this source is displayed properly. 我正在使用OL 3.9.0,并且正确显示了带有此源的矢量图层。 What am I doing wrong? 我究竟做错了什么?

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());
        }
    }
});

If you're looking to fit to the extent try this: 如果你想要fit的程度尝试这个:

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

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM