leaflet加载EPSG:4326瓦片图

581 阅读1分钟

leaflet加载离线瓦片地图,EPSG:4326

import proj4 from 'proj4';
import 'proj4leaflet';
// 1. 定义 EPSG:4326 投影和分辨率(与 OpenLayers 一致)
const resolutions = [
    1.40625, 0.703125, 0.3515625, 0.17578125, 0.087890625,
    0.0439453125, 0.02197265625, 0.010986328125, 0.0054931640625,
    0.00274658203125, 0.001373291015625, 0.0006866455078125,
    0.00034332275390625, 0.000171661376953125, 0.0000858306884765625,
    0.00004291534423828125, 0.000021457672119140625,
    0.000010728836059570312, 0.000005364418029785156,
    0.000002682209014892578, 0.000001341104507446289
];

// 2. 定义 EPSG:4326 的 CRS(坐标系)
const crs = new L.Proj.CRS(
    'EPSG:4326',
    '+proj=longlat +datum=WGS84 +no_defs',
    {
        resolutions: resolutions,
        origin: [-180, -90], // 修正为左下角原点(与 OpenLayers 一致)
        transformation: new L.Transformation(
            1/360,  // 水平缩放系数:360 度 / 256 像素 = 1.40625 度/像素(匹配 resolutions[0])
            0.5,    // 水平偏移:原点在 -180 度,需偏移半个瓦片宽度(256/2=128 像素)
            1/180,  // 垂直缩放系数:180 度 / 256 像素 = 0.703125 度/像素(匹配 resolutions[0])
            0.5     // 垂直偏移:原点在 -90 度,偏移半个瓦片高度
        )
    }
);
// 自定义瓦片坐标转换
const customLayer = L.TileLayer.extend({
    getTileUrl: function(coords) {
        // 获取瓦片坐标
        const z = coords.z;
        const x = coords.x;
        // OpenLayers 和 Leaflet 的 y 坐标计算方式不同
        // 需要转换 y 坐标
        const y = -1 - coords.y;

        // 返回瓦片路径,根据实际路径格式调整
        return `http://127.0.0.1:8080/test/${z}/${x}/${y}.png`;
    }
});
const map = L.map('map',{
    center: mapCenter.value, // 地图中心
    zoom: 18,   //缩放比列
    zoomControl: true,  //左上角显示放大缩小按钮
    scrollWheelZoom: true, //禁用鼠标滚轮放大缩放
    attributionControl: false,  // 移除右下角leaflet标识
    crs: crs
});

// 创建图层实例
const layer = new customLayer('', {
    tms: true, // 声明使用 TMS 瓦片
    maxZoom: 20,
    tileSize: 256,
    bounds: [[-90, -180], [90, 180]] // 限制瓦片请求范围
});
// 添加图层到地图
layer.addTo(map);