1、通過npm安裝leaflet包,或者直接在項目中引入leaflet.js庫文件。
npm 安裝:npm i leaflet
如果在index.html中引入leaflet.js,在項目中可以直接使用變量L.
注意:盡量要么使用npm包,要么使用leaflet.js庫,兩者一起使用容易發生沖突,引起莫名奇妙的bug.下面以使用leaflet.js庫為例。
2、初始地圖實例
//國家天地圖(矢量)this.layer = L.tileLayer(mapData.layerV)// 國家天地圖(矢量注記)// this.layer2 = L.tileLayer(mapData.layerVZ)//國家天地圖(影像)this.layer3 = L.tileLayer(mapData.layerW);//國家天地圖(影像注記)this.layer4 = L.tileLayer(mapData.layerWZ);L.CRS.CustomEPSG4490 = L.extend({}, L.CRS.Earth, {code: "EPSG:4490",projection: L.Projection.LonLat,transformation: new L.Transformation(1 / 180, 1, -1 / 180, 0.5),scale: function (zoom) {return 256 * Math.pow(2, zoom - 1);},});this.map = L.map(this.id, {crs: L.CRS.CustomEPSG4490,//設置坐標系center: [mapData.mapCenterY, mapData.mapCenterX],zoom: Number(mapData.mapZoom) + 1,maxZoom: 18, //最大縮放層級minZoom: 1, //最小縮放層級tileSize: 256, //切片大小attributionControl: false, // 移除右下角leaflet標識zoomControl: false, //禁用 + - 按鈕// preferCanvas: true, //默認使用svg渲染,設置canvas渲染doubleClickZoom: false, //關閉雙擊縮放layers: [this.layer], //添加地圖圖層// layers: [this.layer, this.layer2], //添加地圖圖層});
<div :id="id" class="map-box"></div>
這里id作為變量,有父組件傳入,可在不同位置引入地圖組件而不發生沖突。
關于地圖的詳細配置參考Documentation - Leaflet - 一個交互式地圖 JavaScript 庫