天地图需要自己去申请key-->步骤为登录天地图官网 --->开发资源下的地图API--->右上角的控制台--->创建新应用(填好之后就会出现key)
安装openlayers (示例中openlayers版本为6.15.1,版本过高时可能会报 ol/ol.css这里面的错误)
npm i -S ol@^6.15.1
效果展示
代码如下
<template>
<div id="map">
<el-radio-group v-model="radio" class="radio">
<el-radio :label="1">高德地图</el-radio>
<el-radio :label="2">天地图</el-radio>
</el-radio-group>
</div>
</template>
<script>
// initMap:初始化底图 hideLayersId:隐藏底图 showLayersId:显示底图
import { initMap, hideLayersId, showLayersId } from '../utils/mapUntils'
export default {
data() {
return {
map: null,
radio: 1
}
},
mounted() {
this.map = initMap('map')
},
watch: {
radio: {
handler(val) {
console.log(val)
// 高德地图
if (val === 1) {
hideLayersId(this.map, 'tianditu_lw')
hideLayersId(this.map, 'tianditu_bz')
showLayersId(this.map, 'gaodeditu')
} else {
hideLayersId(this.map, 'gaodeditu')
showLayersId(this.map, 'tianditu_lw')
showLayersId(this.map, 'tianditu_bz')
}
},
deep: true
}
},
destroyed() {
this.map = null
}
}
</script>
<style lang="scss" scoped>
#map{
width: 100%;
height: 100%;
position: relative;
.radio{
position: absolute;
right: 10px;
top: 10px;
z-index: 222;
background: #fff;
height: 40px;
line-height: 40px;
width: 128px;
.el-radio{
margin: 0;
display: block;
width: 100%;
height: 20px;
line-height: 20px;
text-align: left;
text-indent: 6px;
}
}
}
</style>
import 'ol/ol.css'
import { Map, View } from 'ol'
import TileLayer from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ'
export function initMap(id) {
const tianditu_lw = new TileLayer({
title: '天地图路网',
crossOrigin: 'anonymous', // 是否请求跨域操作
wrapX: false,
source: new XYZ({
url: 'https://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=你自己的key'
}),
id: 'tianditu_lw',
visible: false,
isGroup: true,
name: '天地图路网'
})
const tianditu_bz = new TileLayer({
title: '天地图文字标注',
attributions: '天地图的属性描述',
wrapX: false,
source: new XYZ({
url: 'https://t0.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=你自己的key'
}),
id: 'tianditu_bz',
visible: false,
isGroup: true,
name: '天地图文字标注'
})
// 高德地图
const gaodeditu = new TileLayer({
title: 'BASE_LAYER',
source: new XYZ({
url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=6&x={x}&y={y}&z={z}',
wrapX: true
}),
id: 'gaodeditu',
visible: true
})
const map = new Map({
target: id,
layers: [tianditu_lw, tianditu_bz, gaodeditu],
view: new View({
projection: 'EPSG:4326',
center: [112.064839, 32.548857],
zoom: 5
})
})
return map
}
// 隐藏图层
export function hideLayersId(map, id) {
const layers = map.getLayers().getArray()
const layer = layers.find(item => item.values_.id === id)
if (layer) {
layer.setVisible(false)
}
}
// 显示图层
export function showLayersId(map, id) {
const layers = map.getLayers().getArray()
const layer = layers.find(item => item.values_.id === id)
if (layer) {
layer.setVisible(true)
}
}