I originally wrote some code using the 4.3 Javascript API to make the Legend widget visible only at certain scales of the map view:
When using version 4.3 of the Javascript API, this code works: the Legend changes its visibility at the appropriate scale.
When using version 4.6 of the Javascript API, this code breaks: the Legend always remains visible, but switches between displaying the layer properties and displaying "No legend," rather than disappearing as it did before.
How can I mimic the functionality of 4.3 in version 4.6?
Thanks for the help!
Philip
Solved! Go to Solution.
Phillip,
you can use this:
view.watch("scale", function(scale) {
if (scale > 1500000) {
legend.container.style.display = 'none';
} else {
legend.container.style.display = '';
}
});
Phillip,
you can use this:
view.watch("scale", function(scale) {
if (scale > 1500000) {
legend.container.style.display = 'none';
} else {
legend.container.style.display = '';
}
});
That works. Thanks for the quick solution, Robert!
Actually, one last question: is there a way to initialize the Legend widget so that it has its display set to 'none'?
Currently, the map loads and the "No legend" box is present until the user changes scales.
I'm having trouble accessing the display property when creating the Legend widget.
Thanks again for the help!
Philip,
That would involve using watchUtils. Here is a sample:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>Legend widget - 4.6</title>
<link rel="stylesheet" href="https://js.arcgis.com/4.6/esri/css/main.css">
<style>
html,
body,
#viewDiv {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
overflow: hidden;
}
</style>
<script src="https://js.arcgis.com/4.6/"></script>
<script>
require([
"esri/views/MapView",
"esri/widgets/Legend",
"esri/WebMap",
"esri/core/watchUtils",
"dojo/domReady!"
],
function(
MapView, Legend, WebMap, watchUtils
) {
var webmap = new WebMap({
portalItem: { // autocasts as new PortalItem()
id: "4abe6a830b8f466dacf8abfde567a781"
}
});
var view = new MapView({
container: "viewDiv",
map: webmap
});
view.when(function() {
// get the first layer in the collection of operational layers in the WebMap
// when the resources in the MapView have loaded.
var featureLayer = webmap.layers.getItemAt(0);
var legend = new Legend({
view: view,
layerInfos: [{
layer: featureLayer,
title: "NY Educational Attainment"
}]
});
watchUtils.when(legend ,"container", function(){
legend.container.style.display = 'none';
})
// Add widget to the bottom right corner of the view
view.ui.add(legend, "bottom-right");
view.watch("scale", function(scale) {
if (scale > 1500000) {
legend.container.style.display = 'none';
} else {
legend.container.style.display = 'block';
}
});
});
});
</script>
</head>
<body class="calcite">
<div id="viewDiv"></div>
</body>
</html>
Got it. Thanks again, Robert!