Openlayers示例7 | Attributions

Attributions

当地图因调整大小而变得太小时,属性将被折叠。这是因为当地图的宽度小于600像素时,可折叠选项被设置为true。

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

<head>
  <meta charset="UTF-8">
  <!-- 引入OpenLayers CSS样式 -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.13.0/css/ol.css"
    type="text/css">
  <!-- 引入OpenLayers JS库 -->
  <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.13.0/build/ol.js"></script>
  <!-- css代码 -->
  <style type="text/css">
    .map {
      width: 100%;
      height: 600px;
    }
  </style>
  </style>
  <title>Attributions</title>
</head>
<body>
  <div id="map" class="map"></div>
</body>
<script>
  // https://openlayers.org/en/latest/apidoc/module-ol_control_Attribution-Attribution.html
  const attribution = new ol.control.Attribution({
    collapsible: false,  // 指定是否可以折叠属性。如果未指定,源将通过其 attributionsCollapsible设置控制此行为。
  });
  const map = new ol.Map({
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM(),
      }),
    ],
    // ol.control.defaults() 默认情况下包含在地图中的一组控件。除非另有配置,否则这将返回一个集合,其中包含每个控件
    // https://openlayers.org/en/latest/apidoc/module-ol_control.html#.defaults
    controls: ol.control.defaults({ attribution: false }).extend([attribution]),  // 先把默认的设置为不显示,在通过extend来继承
    target: 'map',
    view: new ol.View({
      center: [0, 0],
      zoom: 2,
    }),
  });

  function checkSize() {
    // 通过判断small是true还是false来设置属性信息是否折叠
    const small = map.getSize()[0] < 600;
    attribution.setCollapsible(small); // 指定是否可以折叠属性。如果未指定,源将通过其 attributionsCollapsible设置控制此行为。
    attribution.setCollapsed(small);  // 指定是否应在启动时折叠属性。
  }

  window.addEventListener('resize', checkSize);
  checkSize();

</script>
</html>
posted @ 2022-03-20 15:40  槑孒  阅读(351)  评论(0编辑  收藏  举报