Search code examples
zoomingopenlayerskml

show/hide kml on defined zoom levels


I´m trying to hide/show my own kml files (polygons) depending on zoom levels in OpenLayers - when reached certain zoom level one layer should hide and another show. So far I found this solution (How to load layers depending on zoom level?), but it doesn´t seem to be working in my case. I´m relatively new to javascript and I don´t know if I´m using this right, I also made some changes to the example:

map.events.register("zoomend", map, zoomChanged);   //inserted in function init()

function zoomChanged()
    {
      if (map.getZoom() == 18)
      {
      kml1.setVisibility (true);
      kml2.setVisibility (false);
      }
      else if (map.getZoom() == 19)
      {
      kml1.setVisibility (false);
      kml2.setVisibility (true);
      }
    }

I also tried another solution to hide kml1, but in this case my layer isn´t drawn. The LayerSwitcher works - the layer is unselectable in defined zoom levels, but nothing is visible when zoomed out (when layer is already selectable):

var kml1 = new OpenLayers.Layer.Vector("prehled", 
                {minScale: 1000,},                                //1:1000
                {
                projection: map.displayProjection,
                strategies: [new OpenLayers.Strategy.Fixed()],
                protocol: new OpenLayers.Protocol.HTTP({
                    url: "kml/zahrada.kml",
                    format: new OpenLayers.Format.KML({
                        extractStyles: true,
                        extractAttributes: true,
                    })
                })
            });
    map.addLayer(kml1);

Thanks for any response and advice on this.


Solution

  • Try:

    var kml1 = new OpenLayers.Layer.Vector("prehled", {
                minResolution: map.getResolutionForZoom(18), // or the desired maximum zoom
                projection: map.displayProjection,
                strategies: [new OpenLayers.Strategy.Fixed()],
                protocol: new OpenLayers.Protocol.HTTP({
                    url: "kml/zahrada.kml",
                    format: new OpenLayers.Format.KML({
                        extractStyles: true,
                        extractAttributes: true
                    })
                })
            });
    map.addLayer(kml1);
    

    ```