1 需求描述

现在有这么一个需求:在地图中添加一些图层,添加图层列表按钮。打开图层列表后用户会打开某些图层使其可见,要求关闭图层列表时,隐藏某些图层(若visible=true)

2 解决方案

可以使用 ArcGIS API for JavaScript 的 dojo/on 模块来监听按钮的点击事件,控制图层的visible属性。

关键代码:

// 添加按钮
var toggleLayerBtn = document.getElementById("toggleLayerBtn");
view.ui.add(toggleLayerBtn, "top-right");

// 监听按钮点击事件,若图层可见,则关闭
on(toggleLayerBtn, "click", function() {
  if (myFeatureLayer .visible) {
    myFeatureLayer .visible = false;
  } 
});

完整代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>ArcGIS API for JavaScript: Custom Button to Toggle Layer Visibility</title>
    <link rel="stylesheet" href="https://js.arcgis.com/4.16/esri/css/main.css">
    <script src="https://js.arcgis.com/4.16/"></script>
  </head>
  <body>
    <div id="map"></div>
    <button id="toggleLayerBtn">Toggle Layer</button>

    <script>
      require([
        "esri/Map",
        "esri/views/MapView",
        "esri/layers/FeatureLayer",
        "dojo/on",	//用于监听按钮点击事件
        "dojo/domReady!"
      ], function(Map, MapView, FeatureLayer, on) {
        // Create the map and set the view
        var map = new Map({
          basemap: "topo-vector"
        });
        var view = new MapView({
          container: "map",
          map: map,
          center: [0, 0],
          zoom: 4
        });

        // 添加图层
        var myFeatureLayer = new FeatureLayer({
          url: "https://example.com/path/to/feature/layer",
          title: "My Feature Layer",
          visible: false
        });
        map.add(myFeatureLayer );

        // 添加按钮
        var toggleLayerBtn = document.getElementById("toggleLayerBtn");
        view.ui.add(toggleLayerBtn, "top-right");

        // 监听按钮点击事件,若图层可见,则关闭
        on(toggleLayerBtn, "click", function() {
          if (myFeatureLayer .visible) {
            myFeatureLayer .visible = false;
          } 
        });
      });
    </script>
  </body>
</html>

上面的示例代码首先创建了一个地图和地图视图,然后创建了一个FeatureLayer并将其添加到地图中。接下来,使用 dojo/on 模块监听按钮的点击事件,在点击时检查FeatureLayer是否可见,若可见,则 myFeatureLayer .visible = false。

注意替换 “https://example.com/path/to/feature/layer” 为你的FeatureLayer的 URL。

10-07 14:29