静态 Attribution
静态 Attribution示例。 attributions OpenStreetMap
本示例展示如何添加一个永远不会从地图上消失的 attribution。它的实现方式是在 attribution 选项中传入一个静态字符串或 HTML 字符串,该字符串不与图层关联。点击“Toggle layer”按钮可以看到,即使所有图层都关闭,静态 attribution 仍然显示在屏幕上。
main.js
js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import Attribution from 'ol/control/Attribution.js';
import {defaults as defaultControls} from 'ol/control/defaults.js';
import TileLayer from 'ol/layer/Tile.js';
import OSM from 'ol/source/OSM.js';
const attribution = new Attribution({
collapsible: false,
attributions: `<a href="https://openlayers.org">I'm a static attribution. I never disappear</a>`,
});
const map = new Map({
layers: [
new TileLayer({
source: new OSM(),
}),
],
controls: defaultControls({attribution: false}).extend([attribution]),
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
document.getElementById('toggleLayerButton').addEventListener('click', () => {
map.getLayers().forEach((l) => {
l.setVisible(l.getVisible() ? false : true);
});
});index.html
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>静态 Attribution</title>
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<button id="toggleLayerButton">切换图层</button>
<script type="module" src="main.js"></script>
</body>
</html>package.json
json
{
"name": "static-attribution",
"dependencies": {
"ol": "10.11.0"
},
"devDependencies": {
"vite": "^8.1.5"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}