【问题标题】:How to get the extent of a GeoJSON vector source?如何获取 GeoJSON 矢量源的范围?
【发布时间】:2015-09-15 11:49:18
【问题描述】:

我有这个 GeoJSON 文件 (polygon.geojson)...

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

...并将其用作矢量源:

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

现在我想通过以下方式获取范围:

var extent = vectorSource.getExtent();

但是,extent 的值是:

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

我正在使用 OL 3.9.0,并且带有此源的矢量图层可以正确显示。我做错了什么?

【问题讨论】:

  • 您可以尝试将ol.js 替换为ol-debug.js 并进入getExtent 方法以真正查看发生了什么(使用您的浏览器开发工具)。也许这会有所帮助。
  • 确定不使用useSpatialIndex或者在矢量源加载任何特征之前调用方法?
  • 当我想计算范围时,可能数据还没有加载(我注意到在页面加载后打开Web控制台时设置了范围)。如何检查数据是否已加载?

标签: javascript openlayers-3


【解决方案1】:

我想通了。我需要等到源加载完毕:

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

编辑:仅当图层不为空时缩放可能更安全:

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

【讨论】:

  • 已确认正在开发 3.15.1。
  • 正是我正在寻找并且仍在为 openlayers 6.3.1 工作的内容
【解决方案2】:

如果您希望 fit 达到一定程度,请尝试以下操作:

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

【讨论】:

  • 是的,这就是我试图实现的目标。但是,我得到TypeError: Argument 2 of CanvasRenderingContext2D.putImageData is not a finite floating-point value.
【解决方案3】:

您可以为每个特征循环并创建计算边界,如下所示:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多