Search code examples
javascriptzoomingopenlayers

Openlayers zoom-based object visibility not working


I would like to have my element zoom-based. I don't need it visible when zooming out of 19, because my map doesn't look nice.

enter image description here

I tried to use the maxResolution method derived from the layers.js file, when it was found, as a whole map was generated by the QGIS2web plugin. Unfortunately it wasn't working

I tried also the minZoom feature, but in vain.

All the reasonable examples I found here:

https://openlayers.org/en/latest/apidoc/module-ol_View.html

https://openlayers.org/en/latest/examples/layer-zoom-limits.html

https://github.com/Viglino/ol-ext/issues/51

Another thread says about changing the maxResolution value, but it didn't work either.

https://gis.stackexchange.com/questions/160725/vector-layer-visibility-using-min-maxresolution-is-not-working-in-openlayers-2

Finally, my code looks as follows:

   var tekst2 = new ol.Overlay({
   position: pos3,
   minZoom: 19,
   element: document.getElementsByClassName('tekscio')[1],
   });
   map.addOverlay(tekst2);

I see, that the minZoom refers mostly for the lower zoom limit of the map canvas.

But this configuration:

  var tekst2 = new ol.Overlay({
  position: pos3,
  element: document.getElementsByClassName('tekscio')[1],
  maxResolution:0.42006699228392946,
  });
  map.addOverlay(tekst2);

didn't work either.

I also found some methods here:

http://dev.openlayers.org/releases/OpenLayers-2.13.1/doc/apidocs/files/deprecated-js.html

http://dev.openlayers.org/docs/files/OpenLayers/Layer/FixedZoomLevels-js.html#OpenLayers.Layer.FixedZoomLevels.getOLZoomFromMapObjectZoom

but it looks like they have been deprecated.

What should I do in this code? Is there another thing to provide here, which I am missing?

I want to have this text based on the zoom level.

Just in case I am sending the JS fiddle with the javascript code here:

https://jsfiddle.net/uxkcyomf/


Solution

  • I would like to have my element zoom-based. I don't need it visible when zooming out of 19, because my map doesn't look nice.

    You can simply show/hide an element depending on the current zoom level in a way similar to this (the zoom change handler was taken from https://gis.stackexchange.com/a/309404/70847):

    var currZoom = map.getView().getZoom();
    map.on("moveend", function(e) {
      var newZoom = map.getView().getZoom();
      if (currZoom != newZoom) {
        if (newZoom > 19) {
            document.getElementById("vienna").style.display = "none";
        } else {
            document.getElementById("vienna").style.display = "unset";
        }
        currZoom = newZoom;
      }
    });