Search code examples
openlayersopenlayers-3

How to change zoom level text in Openlayer?


I am trying to show current zoom level on the screen.

I can get initial zoom value, but I want to change this value when map is changed.

Vue.component('zoomlevel', {
    data:function(){
        return this.setDefault();
    },
    methods:{
        setDefault:function(){
            return {
                lang:lang.signin,
                onoff:true,
                zoom:GeoName.map.getView().getZoom(),
                scale:"Scale"
            }
        },
        open:function(){
            this.zoom=GeoName.map.getView().getZoom();
        },
        close:function(){
            this.onoff=false;
        }
    },
    template:
      '<div v-if="onoff" class="digitalScale2">Zoom Level: {{zoom}}</div>'
});
var zoomlevel = new Vue({ el: '#zoomlevel' });

How can I do that?


Solution

  • I was just posting the answer when I see the @Anatoly answer. I will add one more alternative, you can subscribe to moveend event of the map or you can subscribe to change:resolution of the view. Take a look at the example I made for you,

    <!doctype html>
    <html lang="en">
      <head>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/css/ol.css" type="text/css">
        <style>
          .map {
            height: 400px;
            width: 100%;
          }
    			#a { display: none; }
        </style>
        <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/build/ol.js"></script>
        <title>Click Pixel Coord</title>
      </head>
      <body>
        <h2>Zoom Level On Change</h2>
        <p id="p"></p>
        <div id="map" class="map"></div>
    		<script type="text/javascript">
    		var currentZoom = 4;
        var view = new ol.View({
          center: ol.proj.fromLonLat([37.41, 8.82]),
          zoom: currentZoom
        });
        var map = new ol.Map({
    			target: 'map',
    			layers: [
    				new ol.layer.Tile({
    					source: new ol.source.OSM()
    				})
    			],
    			view
    		});
        document.getElementById('p').innerHTML = `Level:${currentZoom}`;
        map.on('moveend', function(evt) {
          var zoom = view.getZoom();
          console.log(`map->moveend->zoom ${zoom}`);
          if (zoom !== currentZoom) {
            currentZoom = zoom;
            document.getElementById('p').innerHTML = `Level:${currentZoom}`;
          }
        });
        view.on('change:resolution', function(evt) {
          var zoom = view.getZoom();
          console.log(`view->resolution->zoom ${zoom}`);
        });
        </script>
      </body>
    </html>