在vue项目中引入地图的方法有多种,如天地图,vue-amap等,各有优略,大家可以根据自己的需要来选择。
本次介绍的是自己公司使用的天地图。(官网:https://ditu.zjzwfw.gov.cn/docs/#/README )
因为在官网中只有属性,方法的介绍,没有详细的引入教程,所以自己用了之后写一篇文档防止和我一样的小伙伴走弯路。
详细情况如下所示。
第一步是按照官网拿到自己的key(密钥)
第二步是在你的vue项目中的 index.html 中引入对应的src。如下所示
<script src="//api.tianditu.gov.cn/api?v=4.0&tk=396a532e3cc05a260931d1b308636316"></script>
第三步就是建一个js文件 Map.js ,方便天地图的引入,此文件可以放在你方便引入的位置。Map.js 中代码如下
// 初始化地图 export default { init() { return new Promise((resolve, reject) => { // 如果已加载直接返回 if (window.T) { console.log('地图脚本初始化成功...') resolve(window.T) reject('error') } }) } }
第四步就可以在使用的vue页面中引用了。代码如下
<template>
<div class="home">
<div id="bdmap" class="map" style ="position:absolute;bottom:0px;top:0px;width:100%"></div>
</div>
</template>
<script>
import MapInit from "@/components/Map.js"
export default {
data(){
return{
map: null,
}
},
created(){
this.init()
},
methods:{
init(){
MapInit.init().then(
T => {
this.T = T;
const imageURL = "http://t0.tianditu.gov.cn/img_c/wmts?tk=您的密钥";
const lay = new T.TileLayer(imageURL, { minZoom: 1, maxZoom: 18 });
const config = { layers: [lay], name: 'TMAP_SATELLITE_MAP' };
this.map = new T.Map('bdmap', config);
const ctrl = new T.Control.MapType();
this.map.addControl(ctrl);
this.map.centerAndZoom(new T.LngLat(118.62, 28.75), 16)
this.map.addEventListener("zoomend", () => {
console.log(lay.Pe)
});
}).catch()
// 监听缩放级别(缩放后的级别)
}
}
}
</script>
<style>
.map{
width: 100vw;
height: 100%;
position: absolute;
}
</style>
本人也是第一次使用天地图,有大佬看出不合适的还望多多指正!
(参考地址https://blog.csdn.net/Wuyo_7/article/details/107253632)