Search code examples
angulartypescriptopenlayers

Is it possible to lock the center of an openlayers map?


I want to lock the center of my openlayers map. So on initialization I center the map but after that I want the map to stay centered but allow zooming. I disabled the dragPan interaction but with zooming the maps zooms to the position of the mouse instead of the center of the map. Is it possible to change this behavior?


Solution

  • It can be done using a zero width and height center extent constraint:

    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.9.0/css/ol.css" type="text/css">
        <style>
          html, body, .map {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
          }
        </style>
        <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.9.0/build/ol.js"></script>
        <title>OpenLayers example</title>
      </head>
      <body>
        <div id="map" class="map"></div>
        <script type="text/javascript">
          var center = ol.proj.fromLonLat([37.41, 8.82]);
          var map = new ol.Map({
            target: 'map',
            layers: [
              new ol.layer.Tile({
                source: new ol.source.OSM()
              })
            ],
            view: new ol.View({
              center: center,
              zoom: 4,
              extent: center.concat(center),
              constrainOnlyCenter: true,
              smoothExtentConstraint: false
            })
          });
        </script>
      </body>
    </html>