缩放到一组特征 (OpenLayers 4)

Zoom to set of features (OpenLayers 4)

使用 OpenLayers 4 显示带有 GeoJSON 数据的地图。 在其中显示几个点和多边形特征。现在我只想缩放点特征。如何实现?

我的代码

var map, docketLayer, docketSource;    

docketSource = new ol.source.Vector({
    url:'http://localhost:8080/mapApp/resources/map/fetch?111',
    format: new ol.format.GeoJSON()
});

docketLayer = new ol.layer.Vector({
    source: docketSource,
    style: styleFunction
}); 

map = new ol.Map({
    layers: [docketLayer],
    target: 'map',
    view: new ol.View({
        center: [0, 0],
        zoom: 1
    })
});

function zoomPoints(){
    var extent = docketSource.getExtent();
    map.getView().fit(extent, map.getSize());
}

ol.extent.boundingExtent 是你的朋友。它为给定的所有坐标创建边界范围。

例如:

var coordinates = docketSource.getFeatures()
    .map(function (f) { return f.getGeometry(); })
    .filter(function (g) { return g instanceof ol.geom.Point; })
    .map(function (g) { return g.getCoordinates(); });
var extent = ol.extent.boundingExtent(coordinates);

你只需要小心在源加载功能后调用函数。