如何独立设置feature和label zIndex

问题描述 投票:0回答:1

我有一张地图,其线条层下方有一个多边形层。但是,我需要多边形标签位于线标签之上,或者在整理方面具有更高的优先级。我发现执行此操作的唯一方法是使多边形图层成为具有两个子图层的图层组,一个用于要素,第二个图层用于 zIndex 高于线图层的标签。有没有更好或更简单的方法来实现这一点?

openlayers
1个回答
0
投票

Layer zIndex 优先于要素 zindex,因此您必须将所有要素加载到一层中。然后使用样式数组进行样式设置,在其中为要素轮廓及其标签设置不同的 zIndex 值。

<html>
<head>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/ol.css">
  <style>
    html,
    body {
      height: 100%;
      margin: 0;
    }
    #map {
      width: 100%;
      height: 100%;
    }
  </style>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/ol.js"></script>
</head>
<body>
  <div id="map" class="map"></div>
  <script>

const geojsonObject = {
  type: 'FeatureCollection',
  crs: {
    type: 'name',
    properties: {
      name: 'EPSG:3857',
    },
  },
  features: [
    {
      type: 'Feature',
      geometry: {
        type: 'LineString',
        coordinates: [
          [-2e6, -2e6],
          [2e6, 2e6],
        ],
      },
    },
    {
      type: 'Feature',
      geometry: {
        type: 'Polygon',
        coordinates: [
          [
            [-2e6, -1e6],
            [2e6, -1e6],
            [0, 1e6],
            [-2e6, -1e6],
          ],
        ],
      },
    },
  ],
};

const vectorSource = new ol.source.Vector({
  features: new ol.format.GeoJSON().readFeatures(geojsonObject),
});

const vectorLayer = new ol.layer.Vector({
  source: vectorSource,
  style: function (feature) {
    const type = feature.getGeometry().getType();
    return [
      new ol.style.Style({
        zIndex: type === 'Polygon' ? 1 : 2,
        stroke: new ol.style.Stroke({
          color: type === 'Polygon' ? 'blue' : 'red',
          width: 10,
        }),
      }),
      new ol.style.Style({
        zIndex: type === 'Polygon' ? 4 : 3,
        text: new ol.style.Text({
          scale: 5,
          text: type,
          fill: new ol.style.Fill({
            color: type === 'Polygon' ? 'blue' : 'red',
          }),
        }),
      }),
    ];
  },
});

const map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM(),
    }),
    vectorLayer,
  ],
  target: 'map',
  view: new ol.View({
    center: [0, 0.25e6],
    zoom: 5,
  }),
});


  </script>
</body>

</html>

© www.soinside.com 2019 - 2024. All rights reserved.