简体   繁体   中英

Zoom to set of features (OpenLayers 4)

Using OpenLayers 4 displaying a map with GeoJSON data. Displaying Few Point and polygon features in it. Now I want to zoom only point features. How do I achieve it?

My Code

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 is your friend. It creates a bounding extent for all coordinates given.

For example:

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

You just have to be careful to call the function after the source has loaded the features.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM