申请天地图key
官方:https://www.tianditu.gov.cn/
申请key:https://sso.tianditu.gov.cn/login?service=https%3A%2F%2Fconsole.tianditu.gov.cn%2F
进去之后,先登录,如果没账号先注册一个就行。
可以创建个应用,创建完成后,会自动生成key。
安装ol加载天地图
先安装下
npm i ol
然后是完整代码:
<template>
<div id="map-container"></div>
</template>
<script>
import { Map, View } from 'ol'
import { Tile as TileLayer } from 'ol/layer'
import { get } from 'ol/proj';
import { getWidth, getTopLeft } from 'ol/extent'
import { WMTS } from 'ol/source'
import WMTSTileGrid from 'ol/tilegrid/WMTS'
export const projection = get("EPSG:4326");
const projectionExtent = projection.getExtent();
const size = getWidth(projectionExtent) / 256;
const resolutions = [];
for (let z = 2; z < 19; ++z) {
resolutions[z] = size / Math.pow(2, z);
}
let map;
export default {
data() {
return {
}
},
mounted(){
this.initMap('SL') // 加载矢量底图
// this.initMap('YX') // 加载影像底图
// this.initMap('DX') // 加载地形晕渲
},
methods:{
initMap(layerType = 'SL') {
const TIANDI_KEY = '31499a6260cb9f29558750d04a934256'
// 对应的值是固定的
const layerTypeMap = {
'SL': ['vec', 'cva'], // [矢量底图, 矢量注记]
'YX': ['img', 'cia'], // [影像底图, 影像注记]
'DX': ['ter', 'cta'] // [地形晕渲, 地形注记]
}
// c: 经纬度投影 w: 球面墨卡托投影
const matrixSet = 'c'
map = new Map({
target: 'map-container',
layers: [
// 底图
new TileLayer({
source: new WMTS({
url: `http://t{0-6}.tianditu.com/${layerTypeMap[layerType][0]}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
layer: layerTypeMap[layerType][0],
matrixSet: matrixSet,
style: "default",
crossOrigin: 'anonymous', // 解决跨域问题 如无该需求可不添加
format: "tiles",
wrapX: true,
tileGrid: new WMTSTileGrid({
origin: getTopLeft(projectionExtent),
//resolutions: res.slice(0, 15),
resolutions: resolutions,
matrixIds: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
})
})
}),
// 标注
new TileLayer({
source: new WMTS({
url: `http://t{0-6}.tianditu.com/${layerTypeMap[layerType][1]}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
layer: layerTypeMap[layerType][1],
matrixSet: matrixSet,
style: "default",
crossOrigin: 'anonymous', // 解决跨域问题 如无该需求可不添加
format: "tiles",
wrapX: true,
tileGrid: new WMTSTileGrid({
origin: getTopLeft(projectionExtent),
resolutions: resolutions,
matrixIds: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
})
})
})
],
view: new View({
center: [169.40, 65.35],
projection: projection,
zoom: 3,
maxZoom: 17,
minZoom: 1
})
})
}
}
}
</script>
<style scoped>
#map-container {
width: 100%;
height: 100%;
}
</style>
上面把天地图密钥替换成你第一步申请的key就可以。
上面示例加载了三种天地图:矢量底图、影像底图、地形晕渲
下面是效果图:
矢量底图
影像底图
地形晕渲