I am building an interactive map where my layers are displayed by zoomlevels using the min/maxResolution property. Here's the simple JS:
function getmap(){
//BaseLayer
function baseMap(){
var baseMap= new ol.layer.Tile({
source: new ol.source.XYZ({
url:'http://{1-
4}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png',
})
})
return baseMap
};
//MainLayer
var layerSource = new ol.source.Vector({
loader: function(extent, resolution, projection) {
var urlSecteur = 'JsonUrl&'
+'bbox='+ extent.join(',');
$.ajax({
url: urlSecteur,
success: function(data) {
var features = geoJSONFormat.readFeatures(data);
layerSource .addFeatures(features);
}
});
},
strategy: ol.loadingstrategy.bbox
});
function createLayer(){
var Layer = new ol.layer.Vector({
title: 'Layer',
source: LayerSource,
minResolution: 0,
maxResolution: 1
})
return Layer
};
//Assembly of layers
var layerBaseMap= baseMap();
var layerLayer = createLayer();
var map = new ol.Map({
target: 'map',
layers: [
layerBaseMap,
layerLayer
],
view: new ol.View({
center: ol.proj.fromLonLat([2.52639, 46.48361]),
zoom: 6,
minZoom: 6,
minZoom: 6
})
};
And the HTML:
<html>
<head>
<!-- Javascript library "openlayer" -->
<link rel="stylesheet" href="/JsLib/openlayer/ol.css" />
<script src="/JsLib/openlayer/ol.js"></script>
<!-- Javascript library "JQuery" -->
<script src="/JsLib/jquery/jquery-3.2.1.js"></script>
<!-- Link JS -->
<script type="text/javascript" src="/JS/mapol.js"> </script>
</head>
<body onload="getmap()">
<div id="legend">
<div id="attribute1">
</div>
<div id="attribute2">
</div>
<div id="attribute3">
</div>
</div>
<div id="map"></div>
<style>
#map {
height: 810px;
width: 1380px;
position: absolute;
top: 106px;
left: 300px;
}
#legend{
display: none;
}
#attribute1{
background-color:rgb(254, 237, 222);
font-family: Arial;
color: white;
height: 40px;
width: 240px;
position: relative;
}
#attribute2{
background-color:rgb(253,208,162);
font-family: Arial;
color: white;
height: 40px;
width: 240px;
position: relative;
}
#attribute3{
background-color:rgb(253,174,107);
font-family: Arial;
color: white;
height: 40px;
width: 240px;
position: relative;
}
</style>
</body>
</html>
What I want to do is to display a legend when the layer gets visible (when the user reach the appropriate zoomlevel). The legend is already set in HTML so I just need to change the display property in CSS from "none" to "block". In theory this should goes like this at the end of the Js:
if(layerLayer.isVisible == true){
legend.style.display="block"
}else{
legend.style.display="none"
};
I have already tried some solutions, noone of these has worked:
if(layerLayer.getVisible() == true){
legend.style.display="block"
}else{
legend.style.display="none"
};
And
if(layerSource.getState() == 'ready'){
legend.style.display="block"
}else{
legend.style.display="none"
};
Both display the legend when the map gets loaded.
Any suggestions?