今天来写个简单的例子。
在地图上添加版权信息,地图容器大小小于600就隐藏,大于600才显示。
首先是加载底图。
controls是地图上的默认控件,可以都设置为false,原本的attribution也设置为false
let osmLayer = new TileLayer({
source: new OSM({
}),
zIndex: 1,
});
const map = new Map({
layers: [osmLayer],
target: "map_id",
view: new View({
projection: "EPSG:4326",
center: [116.389, 39.903],
zoom: 8,
}),
controls: defaultControls({
attribution: false,
zoom: false,
rotate: false,
}),
});
然后自己来创建一个Attribution,collapsible表示是否折叠。
const attribution = new Attribution({
collapsible: false,
});
再加到地图上
map.addControl(attribution)
地图监听一个事件
map.on("change:size", checkSize);
function checkSize() {
const small = map.getSize()[0] < 600;
attribution.setCollapsible(small);
attribution.setCollapsed(small);
}
checkSize();
就可以看到效果了,注意看右下角。
这里有个小坑,一开始我没有引入ol的样式文件,然后怎么设置都不成功,一直是这样。
所以要在main.js里加上ol样式的引入,大家记得引入哦,不要学我。
import "ol/ol.css";
完整代码:
<template>
<div class="box">
<h1>Attributions</h1>
<div id="map_id"></div>
</div>
</template>
<script>
import Map from "ol/Map.js";
import OSM from "ol/source/OSM.js";
import TileLayer from "ol/layer/Tile.js";
import View from "ol/View.js";
import { Attribution, defaults as defaultControls } from "ol/control.js";
export default {
name: "",
components: {},
data() {
return {
map: null,
};
},
computed: {},
created() {},
mounted() {
let osmLayer = new TileLayer({
source: new OSM({}),
zIndex: 1,
});
const map = new Map({
layers: [osmLayer],
target: "map_id",
view: new View({
projection: "EPSG:4326",
center: [116.389, 39.903],
zoom: 8,
}),
controls: defaultControls({
attribution: false,
zoom: false,
rotate: false,
}),
});
const attribution = new Attribution({
collapsible: false,
});
map.addControl(attribution);
function checkSize() {
const small = map.getSize()[0] < 600;
attribution.setCollapsible(small);
attribution.setCollapsed(small);
}
map.on("change:size", checkSize);
checkSize();
},
methods: {},
};
</script>
<style lang="scss" scoped>
#map_id {
width: 100%;
height: 500px;
}
.box {
height: 100%;
}
</style>