Open Layers 3 center the map based on extent on vector layer?

China☆狼群 提交于 2019-12-12 19:17:05

问题


I want to position the center and zoom level of my map depending on the vector layer features (points).

I have a geojson file which is populating my map:

var vectorSource = new ol.source.Vector({
   url: 'assets/js/data.geojson',
   format: new ol.format.GeoJSON(),
   projection: 'ESPG:3857'
});

I now try to get the extent of the vector layer:

vectorSource.once('change', function (e) {
    if (vectorSource.getState() === 'ready') {
        if (vectorLayer.getSource().getFeatures().length > 0) {
            map.getView().fit(vectorSource.getExtent(), map.getSize());
        }
    }
});

How can I get the coordinates of the map based on the layer features and zoom to specific level?

map.setCenter("// Center position of lon,lat based on layer features//");
map.setZoom("// Zoom level according to layer features//");

回答1:


When you use map.getView().fit(...) you're already centering and zooming. Do you want to know the center and zoom after this?

vectorSource.once('change', function(evt){
  if (vectorSource.getState() === 'ready') {
    // now the source is fully loaded
    if (vectorLayer.getSource().getFeatures().length > 0) {
      map.getView().fit(vectorSource.getExtent(), map.getSize());

      console.info(map.getView().getCenter());
      console.info(map.getView().getZoom());
    }
  }
});


来源:https://stackoverflow.com/questions/34041570/open-layers-3-center-the-map-based-on-extent-on-vector-layer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!