微信公众号
打赏作者
OpenLayers教程

OpenLayers加载离线百度地图瓦片,需要转换坐标系才能加载百度地图瓦片。

坐标转换

使用 projzh 来换算坐标系,官方地址:https://github.com/tschaub/projzh

下载百度地图瓦片

下载地址:http://www.wmksj.com/map.html

OpenLayers加载离线百度地图瓦片例子

html文件同目录的tiles文件夹,用于存放离线百度地图瓦片。projzh目录用于存放坐标换算的js。
注意:初始化地图时虽设置有默认zoom层级,但实际计算栅格百度地图瓦片时会不一样,比如默认设置4,会加载5级的百度地图瓦片等,所以如果网页无地图显示时,可以F12查看其具体加载百度地图瓦片的层级,再去下载。

<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>望远网测试 www.wmksj.com</title>
	<script src="projzh/index.min.js"></script>
	<script src="https://cdn.jsdelivr.net/npm/ol@v7.2.2/dist/ol.js"></script>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@v7.2.2/ol.css">
	<style type="text/css">
		html, body, #map_container{
            width: 100%;
            height: 100%;
            overflow: hidden;
            margin:0;
        }
	</style>
</head>
<body>
	<div id="map_container"></div>
</body>

<script>
	const bd09Extent = [-20037726.37, -12474104.17, 20037726.37, 16474104.17];
    const baiduMercator = new ol.proj.Projection({
		code: 'baidu',
		extent: bd09Extent,
		units: 'm',
    });
    ol.proj.addProjection(baiduMercator);
    ol.proj.addCoordinateTransforms(
		'EPSG:4326',
		baiduMercator,
		projzh.ll2bmerc,
		projzh.bmerc2ll
    );
    ol.proj.addCoordinateTransforms(
		'EPSG:3857',
		baiduMercator,
		projzh.smerc2bmerc,
		projzh.bmerc2smerc
    );

    const bmercResolutions = new Array(19);
    for (let i = 0; i < 19; ++i) {
		bmercResolutions[i] = Math.pow(2, 18 - i);
    }
   
    const baiduSource = new ol.source.XYZ({
		projection: 'baidu',
		wrapX: true,
		url: '',
		tileGrid: new ol.tilegrid.TileGrid({
	        minZoom: 3,
	        resolutions: bmercResolutions,
	        origin: [0, 0],
	        extent: bd09Extent,
		}),
		tileUrlFunction: function(tileCoord){
			let x = tileCoord[1];
			let y = -tileCoord[2] - 1;
			const z = tileCoord[0];
			return 'tiles/'+z+'/'+x+'/'+y+'.png';
		},
    });
	
    const baidu = new ol.layer.Tile({
		source: baiduSource,
    });
	
    const map = new ol.Map({
		target: 'map_container',
		layers: [baidu],
		view: new ol.View({
			center: ol.proj.transform(
				[121.48918852071861,31.23421977234498],
				'EPSG:4326',
				'baidu'
	        ),
	        zoom: 4,
	        projection: 'baidu',
		}),
    });
</script>
</html>


联系我们