Openlayers案例5——动态添加图层列表

1. 代码块

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>动态添加图层列表</title>
  <link rel="stylesheet" href="openlayers/css/ol.css">
  <script src="openlayers/build/ol.js"></script>
  <style>
    body,
    html,
    div,
    ul,
    li {
      border: none;
      padding: 0;
      margin: 0;
      font-size: 14px;
      font-family: 'Microsoft YaHei';
    }

    #map {
      width: 100%;
      height: 100%;
      position: absolute;
    }

    .layerControl {
      position: absolute;
      bottom: 5px;
      min-width: 200px;
      max-height: 200px;
      right: 0px;
      top: 5px;
      z-index: 100;
      color: #ffffff;
      background-color: #4c4e5a;
      border-width: 10px;
      border-radius: 10px;
      border-color: #000 #000 #000 #000;
    }

    .layerControl .title {
      font-weight: bold;
      font-size: 15px;
      margin: 10px;
    }

    .layerTree li {
      list-style: none;
      margin: 5px 10px;
    }
  </style>
</head>

<body>
  <div id="map"></div>
  <div id="layerControl" class="layerControl">
    <div class="title"><label for="">地图列表</label></div>
    <ul id="layerTree" class="layerTree"></ul>
  </div>

  <script>
    // 1.创建列表数组
    var layer = new Array(); // map的图层数组
    var layerName = new Array(); // 图层名数组
    var layerVisibility = new Array(); // 可见图层数组

    // 2.创建加载图层列表中的数据函数
    function loadLayersControl(map, id) {
      var treeContent = document.getElementById(id); //获取图层列表容器对象ul
      var layers = map.getLayers(); // 获取地图中所以图层;
      // 2.1 遍历layers,获取图层、名字、可见性,创建li列表
      for (var i = 0; i < layers.getLength(); i++) { // getLength()获取图层个数
        layer[i] = layers.item(i); // 获取集合中第i个图层,循环为layer数组赋值
        layerName[i] = layer[i].get('name'); // 获取图层名字
        layerVisibility[i] = layer[i].getVisible(); // 获取图层可见性,返回布尔值
        var elementLi = document.createElement('li');  // 创建li子节点
        treeContent.appendChild(elementLi); // 添加li子节点到ul
        // 2.2 创建复选框
        var elementInput = document.createElement('input');
        elementInput.type = 'checkbox';
        elementInput.name = 'layers' // name属性值一致才能实现复选
        elementLi.appendChild(elementInput);
        // 2.3 创建label元素
        var elementLabel = document.createElement('label');
        elementLabel.className = 'layer'; // 设置label类名,修改样式
        // 2.3 设置图层名称
        elementLabel.innerHTML = layerName[i]; // 把图层名添加到label
        // 2.4 把label追加到li
        elementLi.appendChild(elementLabel);
        // 2.5 设置图层默认显示
        if (layerVisibility[i]) {
          elementInput.checked = true; // 如果图层可见,勾选复选框
        };
        // 2.6 为checkbox添加变更事件监听函数
        addChangeEvent(elementInput, layer[i]);
      }
    };

    // 3.为checkbox绑定点击事件
    function addChangeEvent(element, layer) {
      element.addEventListener('click', function () {
        if (element.checked) {
          layer.setVisible(true);
        } else {
          layer.setVisible(false);
        }
      });
    }

    // 4.加载地图
    var map = new ol.Map({
      target: 'map',
      layers: [
        new ol.layer.Tile({
          source: new ol.source.OSM({
            wrapX: false,
          }),
          name: '世界地图OSM瓦片',
          preload: Infinity,
        }),
        new ol.layer.Vector({
          source: new ol.source.Vector({
            url: 'data/geojson/countries.geojson',
            format: new ol.format.GeoJSON(),
          }),
          name: '国界JSON格式的矢量图',
        }),
        new ol.layer.Vector({
          source: new ol.source.Vector({
            url: 'data/kml/MasterArea.kml',
            format: new ol.format.KML({
              extractStyles: false // 不显示kml默认样式
            })
          }),
          name: '点(KML格式矢量图)'
        })
      ],
      view: new ol.View({
        center: [0, 0],
        zoom: 2
      })
    });

    // 5.加载图层列表中的数据
    loadLayersControl(map, 'layerTree');

  </script>
</body>

</html>

2. 效果图

在这里插入图片描述
加载本地数据会面临跨域问题,方法参照解决本地浏览器运行项目的跨域问题

参考:郭明强, 黄颖. WebGIS之OpenLayers全面解析第2版, 电子工业出版社.

文件列表: OL3Demo\.DS_Store OL3Demo\css\base.css OL3Demo\css\js_demo.css OL3Demo\css\ol.css OL3Demo\demos\.DS_Store OL3Demo\demos\Controls\Animation.htm OL3Demo\demos\Controls\CanvasTiles.htm OL3Demo\demos\Controls\FullScreen.htm OL3Demo\demos\Controls\LayerControl.htm OL3Demo\demos\Controls\LayerSpy.htm OL3Demo\demos\Controls\Measure.htm OL3Demo\demos\Controls\MousePosition.htm OL3Demo\demos\Controls\Operation.htm OL3Demo\demos\Controls\OverviewMap.htm OL3Demo\demos\Controls\ScaleLine.htm OL3Demo\demos\Controls\ZoomSlider.htm OL3Demo\demos\data\geojson\countries-110m.json OL3Demo\demos\data\geojson\countries.geojson OL3Demo\demos\data\geojson\GeoJSON.json OL3Demo\demos\data\geojson\samples.json OL3Demo\demos\data\geolocation-orientation.json OL3Demo\demos\data\geolocation_marker_heading.png OL3Demo\demos\data\gml\gml.xml OL3Demo\demos\data\gml\topp-states-wfs.xml OL3Demo\demos\data\gpx\fells_loop.gpx OL3Demo\demos\data\kml\2012-02-10.kml OL3Demo\demos\data\kml\2012_Earthquakes_Mag5.kml OL3Demo\demos\data\kml\kml.xml OL3Demo\demos\DataHandler.ashx OL3Demo\demos\Drawing\DrawFeatures.htm OL3Demo\demos\Drawing\FeaturesStyle.htm OL3Demo\demos\Drawing\ModifyFeatures.htm OL3Demo\demos\Drawing\MoveFeatures.htm OL3Demo\demos\Drawing\SaveFeatures.htm OL3Demo\demos\Labels\AddClusterLabels.htm OL3Demo\demos\Labels\AddLabels.htm OL3Demo\demos\Labels\AddPopup.htm OL3Demo\demos\MultiData\LoadBasicMaps.htm OL3Demo\demos\MultiData\LoadOpenData.htm OL3Demo\demos\MultiData\LoadPublicMaps.htm OL3Demo\demos\MultiData\LoadTiandituMap.htm OL3Demo\demos\MultiData\MapExport.htm OL3Demo\demos\MultiData\OSM.htm OL3Demo\demos\MultiData\OverLayerMaps.htm OL3Demo\demos\OGC\LoadWCSMap.htm OL3Demo\demos\OGC\LoadWFSFeatrue.htm OL3Demo\demos\OGC\LoadWMSMap.htm OL3Demo\demos\OGC\LoadWMTSMap.htm OL3Demo\demos\OGC\WFS_Transaction.htm OL3Demo\demos\Others\AddPOI.htm OL3Demo\demos\Others\CreatCharts.htm OL3Demo\demos\Others\Geolocation.htm OL3Demo\demos\Others\Heatmap.htm OL3Demo\demos\Others\HotSpots.htm OL3Demo\demos\Others\LoadPublicMaps.htm OL3Demo\demos\Others\MilitaryPlotting.htm OL3Demo\demos\Others\MultiViewLinkage.htm OL3Demo\demos\Others\ProjectionTransformation.htm OL3Demo\demos\Others\SimulateGeolocation.htm OL3Demo\demos\Others\副本 LoadPublicMaps.htm OL3Demo\demos\RegDataHandler.ashx OL3Demo\demos\Web.config OL3Demo\images\ArrowIcon\arbitrary_area.png OL3Demo\images\ArrowIcon\arrow.png OL3Demo\images\ArrowIcon\arrow1.png OL3Demo\images\ArrowIcon\arrowcross.png OL3Demo\images\ArrowIcon\assembly.png OL3Demo\images\ArrowIcon\circle.png OL3Demo\images\ArrowIcon\CircleClosedangleCompass.png OL3Demo\images\ArrowIcon\closedangle.png OL3Demo\images\ArrowIcon\curve_flag.png OL3Demo\images\ArrowIcon\custom_arrow.png OL3Demo\images\ArrowIcon\custom_tail_arrow.png OL3Demo\images\ArrowIcon\custom_tail_arrow_.png OL3Demo\images\ArrowIcon\DoubleClosedangleCompass.png OL3Demo\images\ArrowIcon\double_arrow.png OL3Demo\images\ArrowIcon\fourstar.png OL3Demo\images\ArrowIcon\rect_flag.png OL3Demo\images\ArrowIcon\rhombus.png OL3Demo\images\ArrowIcon\SameDirectionClosedangleCompass.png OL3Demo\images\ArrowIcon\singleLine_arrow.png OL3Demo\images\ArrowIcon\smooth_curve.png OL3Demo\images\ArrowIcon\stright_arrow.png OL3Demo\images\ArrowIcon\tail_arrow.png OL3Demo\images\ArrowIcon\triangle.png OL3Demo\images\ArrowIcon\triangle_flag.png OL3Demo\images\ArrowIcon\VaneCompass.png OL3Demo\images\content\dotted.png OL3Demo\images\label\bj.png OL3Demo\images\label\blueIcon.png OL3Demo\images\label\icon.png OL3Demo\images\label\restaurant.png OL3Demo\images\label\国有企业.png OL3Demo\images\left\app.png OL3Demo\images\left\app_current.png OL3Demo\images\left\channel.png OL3Demo\images\left\channel_current.png OL3Demo\images\left\cloud.png OL3Demo\images\left\cloud_current.png OL3Demo\images\left\custom.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值