xyz 瓦片leaflet地图组件 显示
<!DOCTYPE html>
<html>
<head>
<title>XYZ瓦片预览</title>
//引用leaflet 的css 和脚本
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<style>
#map { height: 100vh; }
#info {
position: absolute;
bottom: 10px;
left: 10px;
z-index: 1000;
background: white;
padding: 10px;
border-radius: 5px;
font-family: Arial;
font-size: 14px;
box-shadow: 0 0 5px rgba(0,0,0,0.3);
}
</style>
</head>
<body>
<div id="map"></div>
<div id="info"></div>
<script>
// 初始化地图
const southWest = L.latLng(43, 127.5); // 西南角坐标(纬度, 经度)//请修改
const northEast = L.latLng(46, 131.28); // 东北角坐标
const imgBounds = L.latLngBounds(southWest, northEast);
const map = L.map('map', {
// maxBounds: imgBounds, // 限制地图拖动范围
maxBoundsViscosity: 1.0 // 完全禁止移出边界
}).setView([44.519298, 129.389526], 9); // 初始中心点和缩放级别
// 生成的XYZ瓦片层
L.tileLayer('/v2/slice/{z}/{x}/{y}.png', {
attribution: 'Your Tile Data',
minZoom: 4,
maxZoom: 12,
noWrap: true,
tms: false,// 关键参数:声明使用TMS坐标系
errorTileUrl: createTransparentTile(), // 直接指定透明瓦片URL或Base64
detectRetina: true
// bounds: imgBounds // 仅在此边界内加载瓦片
}).addTo(map);
// 显示地图信息的函数
function updateInfo() {
const center = map.getCenter();
const zoom = map.getZoom();
const bounds = map.getBounds();
// 获取当前视图中心的瓦片坐标
const tileSize = 256; // 标准瓦片大小
const point = map.project(center, zoom);
const x = Math.floor(point.x / tileSize);
const y = Math.floor(point.y / tileSize);
// 计算中心点像素坐标(相对于地图容器)
const pixelX = Math.floor(point.x);
const pixelY = Math.floor(point.y);
//map.setView([center.lat,center.lng],zoom);
document.getElementById('info').innerHTML = `
<strong>影像中心点:</strong><br>
经纬度: ${center.lat.toFixed(6)}, ${center.lng.toFixed(6)}<br>
<strong>影像范围:</strong><br>
西南: ${bounds.getSouthWest().lat.toFixed(4)}, ${bounds.getSouthWest().lng.toFixed(4)}<br>
东北: ${bounds.getNorthEast().lat.toFixed(4)}, ${bounds.getNorthEast().lng.toFixed(4)}<br>
<strong>缩放级别:</strong> ${zoom}<br>
<strong>中心瓦片坐标:</strong> x=${x}, y=${y}
`;
}
// 生成透明瓦片(Base64编码的1x1透明PNG)
function createTransparentTile() {
return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';
}
// 添加地图移动和缩放事件监听
map.on('moveend zoomend', updateInfo);
// 初始化显示信息
updateInfo();
</script>
</body>
</html>