首先,我用的是vue项目,引入的静态资源,因为我觉得安装依赖后按需引入特别麻烦
html
<div id="map">
<div class="tool">
<div @click="addLayer('dt')" :class="{active: toolName == 'dt'}">
地图
</div>
<div @click="addLayer('wxt')" :class="{active: toolName == 'wxt'}">
卫星
</div>
<div @click="addLayer('dxt')" :class="{active: toolName == 'dxt'}">
地形
</div>
</div>
<slot></slot>
</div>
然后是js,先初始化一下地图,初始化后放一个监听图层加载完毕的回调函数(可以不加,随意),我在初始化的时候只加载了天地图的基础样式底图加上文字标注图层
initOpenLayer() {
this.map = new ol.Map({
layers: [
//天地图图层
new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'https://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=你的key',
}),
className: 'dt',
zIndex: 9
}),
//天地图文字图层
new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'https://t0.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=你的key'
}),
className: 'txt',
zIndex: 10
}),
],
target: "map",
view: new ol.View({
//这里面没有转坐标的方法,不知道对不对,求指导
center: [120.14805, 30.26971],
projection: ol.proj.get("EPSG:4326"),
zoom: 13,
maxZoom: 17,
minZoom: 1
})
});
//全屏控件
this.map.addControl(new ol.control.FullScreen());
this.map.on('rendercomplete', (evt) => {
//图片加在图层完成回调
this.$emit('load', this.map);
});
}
如果开始的时候直接都加载进来会比较慢,所以点击的时候再添加图层
addLayer(type) {
this.toolName = type;
let flag = true;
const layers = this.map.getLayers().array_;
layers.forEach(item => {
item.setZIndex(1);
if (item.className_ == type) {
item.setZIndex(9);
flag = false;
}
if (item.className_ == 'txt') {
item.setZIndex(10)
}
});
if (flag) {
if (type == 'dxt') {
this.map.addLayer(
//天地图地形图
new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'https://t0.tianditu.gov.cn/DataServer?T=ter_w&x={x}&y={y}&l={z}&tk=你的key'
}),
className: 'dxt',
zIndex: 7
})
)
} else if (type == 'wxt') {
//卫星图
this.map.addLayer(
new ol.layer.Tile({
source: new ol.source.XYZ({
url: 'https://t0.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=你的key'
}),
className: 'wxt',
zIndex: 8
})
)
}
}
}
这里是添加图层的方法,需要判断是否添加过某一类型图层,如果没加过则添加,如果添加过则将其zIndex调整值最高
有需要改进的地方请留言指出,谢谢