5

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//");
GrizzlyManBear
  • 647
  • 8
  • 16
Nicolas T
  • 327
  • 1
  • 5
  • 15

1 Answers1

11

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());
    }
  }
});
Jonatas Walker
  • 13,583
  • 5
  • 53
  • 82
  • I did not realised that! thought I still had to apply a setCenter to it. This is now resolved! Thanks! – Nicolas T Dec 02 '15 at 12:52
  • 2
    Take a look at the [fit](http://openlayers.org/en/master/apidoc/ol.View.html#fit) method, there are some options. You're welcome. – Jonatas Walker Dec 02 '15 at 12:54