1.天地图官网获取秘钥,并在项目中动态配置秘钥
(1)在页面中创建存放天地图的盒子
<div class="map-address">
<div id="mapDiv"></div>
</div>
(2)从后端获取秘钥,并在页面中配置
const getToken = async () => {
let result = await reqMapToken('SYS_TIANDITU_TK')
if (result.success == true) {
toToken.value = result.msg
loadTDTjsOnCurrentPage()
}
}
const loadTDTjsOnCurrentPage = () => {
let script = document.createElement('script')
script.type = 'text/javascript'
script.src = `http://api.tianditu.gov.cn/api?v=4.0&tk=${toToken.value}`
document.body.appendChild(script)
//在调用天地图方法时需使用定时器
setTimeout(() => {
initMap()
}, 500)
}
(3)初始化天地图
const initMap = () => {
let T = new (window as any).T
//避免天地图重复渲染
if (!map) {
map = T.Map('mapDiv', {
projection: 'EPSG:4326',
})
//配置需要使用的天地图图层
let ctrl = T.Control.MapType([
{
title: '卫星',
icon: ' http://api.tianditu.gov.cn/v4.0/image/map/maptype/satellite.png',
//@ts-ignore
layer: TMAP_SATELLITE_MAP
},
// {
// title: '地图', //地图控件上所要显示的图层名称
// icon: 'http://api.tianditu.gov.cn/v4.0/image /map/maptype/vector.png',
// layer: TMAP_NORMAL_MAP, //地图类型对象,即MapType。
// },
{
title: '卫星混合',
icon: 'http://api.tianditu.gov.cn/v4.0/image/map/maptype/satellitepoi.png',
//@ts-ignore
layer: TMAP_HYBRID_MAP,
},
])
map.addControl(ctrl)
//创建地图显示的中心点
let lnglat = T.LngLat(经度,纬度)
//在页面创建地图,并设置显示级别
map.centerAndZoom(lnglat, 16)
map.setViewport(companyList.value);
}
//移除地图监听事件(防止重复监听数据污染)
map.removeEventListener('zoomend',listenerViewPosition)
map.removeEventListener('moveend',listenerViewPosition)
//清除地图上的所有覆盖物
map.clearOverLays()
}
(4)在地图上添加标注点位
//多点位标注
gateList.map((index: any) => {
//创建标注点位
let lnglats = T.LngLat(经度, 纬度)
//自定义标注点图片
let icons = T.Icon({
//!!!图片地址使用变量定义,否则无效
iconUrl: location,
iconSize: T.Point(22, 22),
iconAnchor: T.Point(10, 20),
})
let marker = T.Marker(lnglats, { icon: icons })
//创建标注对象
map.addOverLay(marker)
//为标注点创建信息窗口
let content = ''
if (index.type) {
content =
"<div style='margin:0px;'><div style='margin:10px 10px; '>" +
index.name +
'<br>' +
index.code +
'</div></div>'
}
//单击标注点展示信息窗口
marker.addEventListener('click', (e: any) => {
let markerInfoWin = T.InfoWindow(content, {
offset: T.Point(0, -10),
}) // 创建信息窗口对象
map.openInfoWindow(markerInfoWin, e.lnglat) //开启信息窗口
})
})
Ps:有不完善的地方还请各位大佬多多指教!