Skip to content

Declutter Group ​

Declutter Group示例。 Mapbox 避让 decluttering 标签 矢量

不同的 declutter 真值可以启用不同的避让分组。如果本示例中矢量图层的 declutter 被设置为 true,那么矢量图层的符号和文本将会阻止下方 Mapbox 样式图层中与其重叠的符号和文本显示。由于这里设置为 "separate"(一个不同于 true 的值),矢量图层会与下方的 Mapbox 样式图层分开进行避让。下方 Mapbox 样式图层的符号和文本可以与矢量图层的符号和文本相互重叠。

main.js
js
import {apply} from 'ol-mapbox-style';
import Feature from 'ol/Feature.js';
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import {getCenter} from 'ol/extent.js';
import Point from 'ol/geom/Point.js';
import {fromExtent} from 'ol/geom/Polygon.js';
import LayerGroup from 'ol/layer/Group.js';
import VectorLayer from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector.js';

const square = [-12e6, 3.5e6, -10e6, 5.5e6];
const overlay = new VectorLayer({
  declutter: 'separate',
  source: new VectorSource({
    features: [
      new Feature({
        geometry: fromExtent(square),
        text: 'Polygon above Mapbox styled layers',
      }),
      new Feature({
        geometry: new Point([-11e6, 4.3e6]),
        text: 'Point above Mapbox styled layers',
      }),
    ],
  }),
  style: {
    'stroke-color': 'rgba(180, 180, 255, 1)',
    'stroke-width': 1,
    'fill-color': 'rgba(200, 200, 255, 0.85)',
    'text-value': ['get', 'text'],
    'text-font': 'bold 14px sans-serif',
    'text-offset-y': -12,
    'text-overflow': true,
    'circle-radius': 5,
    'circle-fill-color': 'rgba(180, 180, 255, 1)',
    'circle-stroke-color': 'rgba(255, 255, 255, 1)',
  },
});

const layer = new LayerGroup();
apply(
  layer,
  'https://api.maptiler.com/maps/streets-v2/style.json?key=Get your own API key at https://www.maptiler.com/cloud/',
);

const map = new Map({
  target: 'map',
  view: new View({
    center: getCenter(square),
    zoom: 3.9,
  }),
  layers: [layer, overlay],
});
index.html
html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>避让分组</title>
    <link rel="stylesheet" href="node_modules/ol/ol.css">
    <style>
      .map {
        width: 100%;
        height: 400px;
      }
      .map .ol-rotate {
        left: .5em;
        bottom: .5em;
        top: auto;
        right: auto;
      }
      .map:-webkit-full-screen {
        height: 100%;
        margin: 0;
      }
      .map:fullscreen {
        height: 100%;
      }
    </style>
  </head>
  <body>
    <div id="map" class="map"></div>

    <script type="module" src="main.js"></script>
  </body>
</html>
package.json
json
{
  "name": "declutter-group",
  "dependencies": {
    "ol": "10.11.0",
    "ol-mapbox-style": "^13.4.1"
  },
  "devDependencies": {
    "vite": "^8.1.5"
  },
  "scripts": {
    "start": "vite",
    "build": "vite build"
  }
}