OL3: Zoom to vector layer on map

DonMarco picture DonMarco · Jan 6, 2014 · Viewed 10.3k times · Source

I have a map with openlayers 3 and a vector layer. I want to map to be resized to this vector layer, but so far all I was able to get was to center the map on the last point of this vector, since the points of the vector layer are not accessible while creating the map:

if (trackMap != null) {
  for (var i = 0; i < trackMap.length; i++) {
    var trackInfo = trackMap[i];
    lat = parseFloat(trackInfo.lat);
    lon = parseFloat(trackInfo.lon);

    var layergpx = new ol.layer.Vector({
      source: new ol.source.Vector({
        parser: new ol.parser.GPX(),
        url: '${contextRoot}/gps/gpx2' + trackInfo.url
      })
    });
    layers.push(layergpx);
    vectorLayers.push(layergpx);
  }
}

map = new ol.Map({
  controls: ol.control.defaults().extend([
    new ol.control.FullScreen()
  ]),
  layers: layers,
  renderer: ol.RendererHint.CANVAS,
  target: 'map',
  view: new ol.View2D({
    center: ol.proj.transform([lon, lat], 'EPSG:4326', 'EPSG:3857'),
    zoom: 13
  })
});

Answer

goodies4uall picture goodies4uall · May 1, 2014

Why not just fit to the extent of the ol.source.Vector?

var source = new ol.source.Vector();

...

map.getView().fitExtent(source.getExtent(), map.getSize());