背景:
在开发过程中,对接wmts服务的时候,调试参数过程中有时候需要直观看到当前地图加载的瓦片的行列号。
实现原理:
利用Leaflet的L.GridLayer图层,加载一个网格图层,重写其createTile方法,来专门显示瓦片的行列号。
代码实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.min.css" rel="stylesheet">
<style>
* {
padding: 0;
margin: 0;
}
html,
body,
#map {
height: 100%;
width: 100%;
overflow: hidden;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
let map;
(function () {
let tdtLayer, gridLayer;
const TK_KEY = '天地图key';
L.CRS.CustomEPSG4326 = L.extend({}, L.CRS.Earth, {
code: 'EPSG:4326',
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);
}
});
map = L.map('map', {
preferCanvas: true,
crs: L.CRS.CustomEPSG4326,
minZoom: 0,
maxZoom: 20,
center: [29.563761, 106.550464],
zoom: 15,
});
initTdtImgLayers()
function initTdtImgLayers() {
const img_c = `http://t1.tianditu.com/img_c/wmts?layer=img&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=${TK_KEY}`;
debugger
tdtLayer = L.tileLayer(img_c, {
tileSize: 256,
attribution: false,
subdomains: [0, 1, 2],
}).addTo(map)
}
tdtLayer.on('load', () => {
initGridLayer()
});
function initGridLayer() {
gridLayer = new L.GridLayer({
attribution: 'Grid Layer',
tileSize: new L.Point(256, 256)
});
gridLayer.createTile = (coords) => {
const tile = L.DomUtil.create('div', 'grid');
const indexStr = [coords.x, coords.y, coords.z].join(', ');
tile.style.outline = '1px solid red';
tile.style.color = 'white';
tile.innerHTML = indexStr;
return tile;
};
gridLayer.addTo(map);
}
})()
</script>
</body>
</html>