上一篇文章介紹了使用openlayers3加載百度在線地圖,對某些項目或應用場景比如不允許上外網的單位,某些項目只針對一定區域地圖加載應用,比如一個縣的地圖,可以采用下載百度瓦片地圖,在服務器或者本機單獨部署的方式進行。
本篇主要講述如何使用openlayers3調用下載的百度離線瓦片地圖。瓦片地圖下載器,網上有很多,在此不做詳細描述。
Openlayers3加載離線百度瓦片地圖,效果以及代碼如下:

代碼如下:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<link rel="stylesheet" type="text/css" href="ol/ol3/css/ol.css" />
<style type="text/css">
body, #mainMap {
border: 0px;
margin: 0px;
padding: 0px;
width: 100%;
height: 100%;
font-size: 13px;
}
</style>
<script type="text/javascript" src="ol/ol3/build/ol-debug.js"></script>
</head>
<body>
<div id="mainMap">
</div>
</body>
</html>
<script type="text/javascript">
// 自定義分辨率和瓦片坐標系
var resolutions = [];
var maxZoom = 18;
// 計算百度使用的分辨率
for (var i = 0; i <= maxZoom; i++) {
resolutions[i] = Math.pow(2, maxZoom - i);
}
var tilegrid = new ol.tilegrid.TileGrid({
origin: [0, 0],
resolutions: resolutions // 設置分辨率
});
// 創建百度地圖的數據源
var baiduSource = new ol.source.TileImage({
projection: 'EPSG:3857',
tileGrid: tilegrid,
tileUrlFunction: function (tileCoord, pixelRatio, proj) {
var z = tileCoord[0];
var x = tileCoord[1];
var y = tileCoord[2];
// 百度瓦片服務url將負數使用M前綴來標識
if (x < 0) {
x = -x;
}
if (y < 0) {
y = -y;
}
return "tiles/" + z + "/" + x + "/" + y + ".png";
}
});
// 百度地圖層
var baiduMapLayer2 = new ol.layer.Tile({
source: baiduSource
});
// 創建地圖
var map =new ol.Map({
layers: [
baiduMapLayer2
],
view: new ol.View({
// 設置成都為地圖中心
center: ol.proj.transform([104.06, 30.67], 'EPSG:4326', 'EPSG:3857'),
zoom: 3
}),
target: 'mainMap'
});
</script>
