首页 > 解决方案 > 为什么 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);
}

标签: openlayers

解决方案


在计算范围之前,需要从 url 加载数据。addfeature添加所有功能后,源将为每个功能读取和事件触发一个事件change,因此您可以使用超时而不是超时

country_provinces.getSource().once('change', function () {
        mapView.fit(country_provinces.getSource().getExtent());
    });

推荐阅读