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

OpenLayers加载离线百度地图瓦片,因百度坐标系特殊,而且其栅格地图瓦片的呈列方式也不一样,所以需要特殊处理。

下载百度地图瓦片

下载全世界百度地图瓦片前几级用于测试,其中选项一定要选“其它使用”,否则到时离线地图会出现一竖条空白。

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

html文件同目录的tiles文件夹,用于存放离线百度地图瓦片。openlayers目录存放js和css文件。

注意:初始化地图时虽设置有默认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>OpenLayers离线百度地图</title>
	<link rel="stylesheet" href="openlayers/ol.css" />
	<script type="text/javascript" src="openlayers/ol.js"></script>
	<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 type="text/javascript">  
	//百度地图
	zoom_x = {3:3,4:5,5:10,6:20,7:39,8:77,9:153,10:306,11:612,12:1224,13:2447,14:4893,15:9785,16:19569,17:39137,18:78273,19:156545}
    var resolutions = [];  
    for (var i = 0; i < 19; i++) {  
        resolutions[i] = Math.pow(2, 18 - i);  
    }  
    var tilegrid = new ol.tilegrid.TileGrid({  
        origin: [0, 0],  
        resolutions: resolutions  
    });  
  
    var baidu_source = new ol.source.TileImage({  
        projection: "EPSG:3857",  
        tileGrid: tilegrid,  
        tileUrlFunction: function (tileCoord, pixelRatio, proj) {  
                if (!tileCoord) {
                    return "";
                }
                let z = tileCoord[0];
                let x = tileCoord[1]
                let y = -tileCoord[2];
				
				let count = 2*zoom_x[z];
				x = x%count;
				if(x>zoom_x[z]-1) {
					x = x - count;
				}else if(x < -zoom_x[z]) {
					x = x + count;
				}
				
                return "tiles/"+z+"/" + x + "/" + y + ".png";
            }
    });  
  
    var baiduMapLayer = new ol.layer.Tile({  
        source: baidu_source  
    });
	var map = new ol.Map({
        target: 'map_container',
        layers: [
          baiduMapLayer
        ],
        view: new ol.View({
			center: ol.proj.fromLonLat([118.398990578125, 30.62840809925475]),
			zoom: 4,
			minZoom: 3,
			maxZoom: 19
        })
    });
</script>
</html>


联系我们