openlayers - 为什么 layer.getSource().getExtent() 需要超时才能工作?
问题描述
[使用 OL 4.6.4] 我需要我的网站放大新加载图层的范围(来自 GeoJSON 的矢量)。如果我在收到断言错误mapView.fit(myLayer.getSource().getExtent())
后立即使用: “Uncaught - Object { message:”Assertion failed. 有关详细信息,请参见https://openlayers.org/en/v4.6.4/doc/errors/#25。”,代码:25,名称:“AssertionError”,堆栈:“”}”map.addLayer(myLayer)
当我通过将其置于超时状态等待呼叫约 1 秒时,它会起作用:
setTimeout(function () {
//calculate extent of loaded data and fit:
mapView.fit(country_provinces.getSource().getExtent());
}, 1000);
但这似乎很愚蠢,而且没有任何地方证明这是必要的。是否有适当的解决方案来放大最近上传的图层?
完整代码:
var navMap;
/*-- Initialization function --*/
function init() {
//define map object & link to placeholder div:
navMap = new ol.Map({target: "map_container"});
// define layer as tiled map:
osmLayer = new ol.layer.Tile({
// load OSM (a connector predefined in the API) as source:
source: new ol.source.OSM()
});
// add layer to map:
navMap.addLayer(osmLayer);
// create a map view:
mapView = new ol.View({
center: ol.proj.transform([0, 0], 'EPSG:4326', 'EPSG:3857'),
zoom: 2
});
navMap.setView(mapView);
navMap.addControl(new ol.control.Zoom());
navMap.addControl(new ol.control.MousePosition({
projection: 'EPSG:4326',
coordinateFormat: ol.coordinate.createStringXY(4)
})
);
var prov_style = new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'MediumPurple',
width: 2
}),
fill: new ol.style.Fill({
color: 'rgba(147, 112, 219, 0.2)'
})
});
country_provinces = new ol.layer.Vector({
source: new ol.source.Vector({
url: '../services/provinces.py',
format: new ol.format.GeoJSON({
defaultDataProjection: 'EPSG:4326',
projection: 'EPSG:3857'
})
}),
style: prov_style,
name: 'Country Provinces'
});
navMap.addLayer(country_provinces);
mapView.fit(country_provinces.getSource().getExtent());
// run a timer (1 sec), in case .getExtent() doe snot work yet:
setTimeout(function () {
//calculate extent of loaded data and fit:
mapView.fit(country_provinces.getSource().getExtent());
}, 1000);
}
解决方案
在计算范围之前,需要从 url 加载数据。addfeature
添加所有功能后,源将为每个功能读取和事件触发一个事件change
,因此您可以使用超时而不是超时
country_provinces.getSource().once('change', function () {
mapView.fit(country_provinces.getSource().getExtent());
});
推荐阅读
- php - 什么是 PHP8 JIT 编译器
- swift - 在 SwiftUI 中旋转文本视图及其框架
- r - 采样一列数据框并在采样输出旁边挑选出值
- wordpress - htaccess 仅通过硬刷新重定向
- python - 从二维数组中提取一个块
- java - 旋转屏幕后如何防止我的 Asynctask 再次执行?
- python - 气流:如何从 PythonOperator 中的 python_callable 内部创建子运算符
- c# - 我不明白 C# 中的字符串
- excel - 错误:此单元格中的数字格式为文本或前面带有撇号
- javascript - Javascript 在 Object.assign() 函数中重命名对象属性