5

I have the following code, written for OpenLayers pre 3.20:

fitViewToFeature: function (viewer, feature) {
    var pan = ol.animation.pan({
      source: viewer.olView.getCenter(),
      duration: 1000
    })

    var zoom = ol.animation.zoom({
      resolution: viewer.olView.getResolution(),
      duration: 1000
    })

    viewer.olMap.beforeRender(pan, zoom)

    viewer.olView.fit(feature.getGeometry(), viewer.olMap.getSize(), {
      padding: [ 100, 100, 100, 100 ],
      constrainResolution: false,
      maxZoom: 4
    })
}

My question is how to translate this function into the new view.animate() syntax introduced in OpenLayers 3.20?

Or alternately, should I open a GitHub issue and request a new option to be added to view.animate?

hyperknot
  • 13,454
  • 24
  • 98
  • 153

2 Answers2

15

You should be able to achieve the same animation in a much simpler way, with the duration option of ol.View#fit():

viewer.olView.fit(feature.getGeometry(), {
  duration: 1000
});

The above works in OpenLayers 4.x.

ahocevar
  • 5,448
  • 15
  • 29
  • Can you update this answer for OL4 to reflect https://github.com/openlayers/openlayers/releases/tag/v4.0.0? I'd be happy to make this one the accepted answer, but it's only compatible with 3.20 right now. – hyperknot May 09 '17 at 22:11
  • Great! Thank you so much! Just to add one thing: you can achieve the same result using feature.getExtent() instead of feature.getGeometry() when working with ol.Image.layer with the extent params set as in my case. Cheers. – umbe1987 Mar 22 '18 at 22:50
  • Its still working at OpenLayers 6.x version. Thanks for comment. – Atakan Savaş Nov 16 '19 at 11:37
0

@zsero, I use the same function to zoom to the extent of a layer source. I use view.animate() for up to half of my route and at the callback function I use view.fit().

I need to setTimeout on the view.fit() otherwise I have an error message: Cannot read property 'length' of null at ol.View.updateAnimations_

var origine = view.getCenter();
var destination = ol.extent.getCenter(extent);
var middleDestination = [(origine[0] + destination[0]) / 2, (origine[1] + destination[1]) / 2];
var viewFit = function() {
    setTimeout( function() {
        view.fit(extent, map.getSize(), {
            duration: duration / 2,
            padding: [ 64, 10, 10, 328 ],
            constrainResolution: false
        })
    }, 0)
}
var animation = function() {
    view.animate({
        center: middleDestination,
        duration: duration / 2
    });
    view.animate({
        zoom: zoom - backZoom,
        duration: duration / 2
    }, viewFit);
}
FatAl
  • 859
  • 1
  • 6
  • 20