使用openlayers加载离线百度地图

177 阅读1分钟
let map = null

const resolutionRange = [0, 19]

function addBaiduLayer() {
    const projection = ol.proj.get('EPSG:3857');
    // 分辨率数组
    const resolutions = []
    for (let i = resolutionRange[0]; i < resolutionRange[1] + 1; i++) {
        resolutions[i] = Math.pow(2, 18 - i)
    }

    const tileGrid = new ol.tilegrid.TileGrid({
        origin: [0, 0],
        resolutions: resolutions
    })
    // 百度地图数据源
    const baiduSource = new ol.source.TileImage({
        projection: projection, // 坐标参考
        tileGrid: tileGrid,
        tilePixelRatio: 1,
        wrapX: false,
        // 瓦片请求方式
        tileUrlFunction: function (tileCoord, pixelRatio, proj) {
            if (!tileCoord) {
                return ""
            }
            const z = tileCoord[0]
            let x = tileCoord[1]
            let y = tileCoord[2]
            if (x < 0) {
                x = (-x)
            }
            if (y < 0) {
                y = (-y)
            }
            return `http://192.168.3.155:8080/tiles/${z}/${x}/${y}.png`
        }
    })
    // 定义全中国的范围(EPSG:3857 投影坐标)
    const chinaExtent = [73.66, 3.86, 135.05, 53.55];
    // const chinaExtent = ol.proj.transformExtent([73, 18, 135, 54], 'EPSG:4326', 'EPSG:3857');
    const baiduLayer = new ol.layer.Tile({
        minZoom: 3,
        maxZoom: 12,
        cacheSize: 256,
        source: baiduSource,
        extent: chinaExtent
    })
    map.addLayer(baiduLayer)
}

function main() {
    map = new ol.Map({
        view: new ol.View({
            minZoom: 3,
            maxZoom: 12,
            center: [120.2, 30.3],
            zoom: 8,
            projection: 'EPSG:4326',
        }),
        layers: [

        ],
        target: 'map_container'
    });
    map.getView().on('change:resolution', function (e) {
        console.log(map.getView().getZoom())
    })
    addBaiduLayer()
}

main()