在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)