效果图:
使用:
<template>
<div id="map" style="width:100vw;height:100vh">
<div
style="
position: fixed;
top: 12vh;
right: 30vw;
z-index: 999;
display: flex;
gap: 5px;
cursor: pointer;
"
>
<LjBaseLayerChange
img="https://smart-garden-manage.oss-cn-chengdu.aliyuncs.com/%E6%A0%85%E6%A0%BC.jpg"
title="影像"
headBgColor="orange"
@handleClick="changeBaseLayer('tianditu')"
></LjBaseLayerChange>
<LjBaseLayerChange
img="https://smart-garden-manage.oss-cn-chengdu.aliyuncs.com/%E7%9F%A2%E9%87%8F.jpg"
title="矢量"
headBgColor="#2196f3"
@handleClick="changeBaseLayer('osm')"
></LjBaseLayerChange>
</div>
</div>
</template>
<script>
import "ol/ol.css";
import { Map, View} from "ol";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import { TileWMS, OSM, XYZ, Vector as VectorSource } from "ol/source";
import { defaults as defaultControls } from "ol/control";
import LjBaseLayerChange from "@/components/LjBaseLayerChange/index.vue";
export default {
name: "",
components: {
LjBaseLayerChange,
},
data() {
return {
map: {},
baselayers: [], //底图
};
},
computed: {},
mounted() {
this.initMap();
},
methods: {
changeBaseLayer(e) {
this.baselayers.forEach((item) => {
if (e !== item.get("name")) {
item.setVisible(false);
return;
}
item.setVisible(true);
});
},
initMap() {
this.baselayers = [
new TileLayer({
name: "tianditu",
source: new XYZ({
url: "http://t3.tianditu.com/DataServer?T=img_w&tk=5a257cd2df1b3311723bd77b0de14baf&x={x}&y={y}&l={z}",
}),
visible: true,
}),
new TileLayer({
name: "osm",
source: new OSM(),
visible: false,
}),
];
this.map = new Map({
layers: [
...this.baselayers, //所有底图
],
target: "map",
view: new View({
projection: "EPSG:4326",
center: [104.29806, 30.5263],
zoom: 18,
}),
controls: defaultControls({ attribution: false, zoom: false }),
});
},
},
watch: {},
};
</script>
LjBaseLayerChange/index.vue:
<!--LjBaseLayerChange-->
<template>
<div
style="width: 35px; height: 35px; position: relative"
@click="changeBaseLayer()"
>
<el-image style="width: 100%; height: 100%" :src="img"></el-image>
<div
style="
position: absolute;
top: 0;
width: 100%;
text-align: center;
color: white;
"
:style="{ backgroundColor: headBgColor }"
>
{{ title }}
</div>
</div>
</template>
<script>
export default {
name: "LjBaseLayerChange",
components: {},
props: {
img: {
type: String,
default: "",
},
title: {
type: String,
default: "标题",
},
headBgColor: {
type: String,
default: "#ff551f",
},
},
data() {
return {};
},
computed: {},
created() {},
mounted() {},
filters: {},
methods: {
changeBaseLayer() {
this.$emit("handleClick");
},
},
watch: {},
};
</script>
<style lang="scss" scoped>
.LjBaseLayerChange {
}
</style>