如何获取 GeoJSON 矢量源的范围?
How to get the extent of a GeoJSON vector source?
我有这个 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,带有此源的矢量图层可以正常显示。我做错了什么?
如果您正在寻找 fit
的程度,试试这个:
var extent = *YOURLAYER*.getSource().getExtent();
map.getView().fit(extent, map.getSize());
我明白了。我需要等到源加载完毕:
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());
}
}
});
您可以循环每个特征并创建计算边界,如下所示:
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());
我有这个 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,带有此源的矢量图层可以正常显示。我做错了什么?
如果您正在寻找 fit
的程度,试试这个:
var extent = *YOURLAYER*.getSource().getExtent();
map.getView().fit(extent, map.getSize());
我明白了。我需要等到源加载完毕:
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());
}
}
});
您可以循环每个特征并创建计算边界,如下所示:
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());