Search code examples
javascriptopenlayersopenlayers-3

Smooth zoom on custom controls Openlayers 3


is it possible to implement smooth zoom in custom button controls.

In example below you can see that there is quite a bit difference in zooming animation between custom and default zooming controls.

var map = new ol.Map({
  target: 'map',
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    })
  ],
  view: new ol.View({
    center: ol.proj.fromLonLat([37.41, 8.82]),
    zoom: 4
  })
});

$('#test1').on('click', function() {
  map.getView().setZoom(map.getView().getZoom() + 1);
});

$('#test2').on('click', function() {
  map.getView().setZoom(map.getView().getZoom() - 1);
});
.map {
  height: 400px;
  width: 100%;
}
<!doctype html>
<html lang="en">

<head>
  <link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
  <style>

  </style>
  <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
  <script src="https://openlayers.org/en/v4.6.5/build/ol.js" type="text/javascript"></script>
  <title>OpenLayers example</title>
</head>

<body>
  <h2>My Map</h2>
  <div>
    <button type="button" id="test1"> plus</button>
    <button type="button" id="test2"> minus</button>
  </div>
  <div id="map" class="map"></div>

</body>

</html>

I'm wondering if it is possible to create same effect smooth effect with custom controls?


Solution

  • You can use animate instead setZoom.
    check view's document, scroll down to animate.
    the code you want will be like:

    view.animate({
      zoom: zoom - 1,
      duration: 200
    });
    

    https://codepen.io/anon/pen/WzZYeE