前端配置: vue + elementui webpack
1.在index.html中引入天地图js文件
<script
src="https://api.tianditu.gov.cn/api?v=4.0&tk=秘钥"
type="text/javascript"
></script>
2.在assets下创建一个技术文件,可自定义名称tianditu.js
export default {
init: function () {
return new Promise((resolve, reject) => {
// 如果已加载直接返回
if (typeof window.T !== 'undefined') {
console.log('地图脚本初始化成功1111...')
resolve(window.T)
return true
}
window.onload = function () {
console.log('地图脚本初始化成功...')
// eslint-disable-next-line
resolve(window.T)
}
})
},
}
3.在页面中引入天地图
<template>
<div class="head">
<!--地图展示-->
<div id="mapDiv" ref="mapDiv" class="mapDiv"></div>
</div>
</template>
<script>
import BaiduMap from '@/assets/tianditu'
data() {
return {
zoom: '12',
line: '',
T: '',
lay: '',
map: '',
polygonTool: '', // 面对象
lineTool: '', // 线对象
longitudeC: '106.58378', // 中心点经度
latitudeC: '29.56674', // 中心点纬度
}
},
mounted() {
setTimeout(this.datainit(), 1000)
},
methods: {
// 初始化地图
datainit: function () {
BaiduMap.init()
.then((T) => {
let _this = this
this.T = T
this.zoom = 16
// 影像底层
var imageURL =
'http://t0.tianditu.gov.cn/img_w/wmts?' +
'SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles' +
'&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=秘钥'
// 影像标注
let bz =
'http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=秘钥'
// 创建自定义图层对象
this.lay = new T.TileLayer(imageURL, { minZoom: 1, maxZoom: 18 })
var config = { layers: [this.lay] }
this.map = new T.Map(this.$refs.mapDiv, config) // 初始化地图对象
let lay1 = new T.TileLayer.WMS(bz, { minZoom: 1, maxZoom: 18 })
this.map.addLayer(lay1) // 添加标注
// 创建线的标注对象
var config1 = {
showLabel: true,
color: '#34d6d7',
}
//创建标注工具对象
this.lineTool = new T.PolylineTool(this.map, config1)
// 创建面的标注工具
var config2 = {
showLabel: true,
color: '#34d6d7',
weight: 3,
opacity: 0.5,
fillColor: '#2e3c57',
fillOpacity: 0.5,
}
//创建标注工具对象
this.polygonTool = new T.PolygonTool(this.map, config2)
if (this.longitudeC == '' && this.latitudeC == '') {
let lc = new T.LocalCity()
lc.location(function (e) {
_this.longitudeC = e.lnglat.lng
_this.latitudeC = e.lnglat.lat
//console.log(_this.longitudeC)
})
_this.map.centerAndZoom(
new T.LngLat(_this.longitudeC, _this.latitudeC),
_this.zoom
) // 设置显示地图的中心点和级别
_this.map.isDrag(true)
_this.map.enableDrag()
_this.map.enableScrollWheelZoom()
})
.catch((error) => {
console.log(error)
})
},
}
4.效果展示