个人认为要点在于view与map层的分辨率要一致。 openlayers默认EPSG:3857,所以使用tileUrlFunction函数自定义瓦片行列号,使之符合百度瓦片规则。
步骤:
- 创建地图容器
<div id="map"></div>
- 定义百度地图分辨率与瓦片网格
Math.pow(2, 18 - i)
- 创建地图实例
new ol.Map
- 指定要添加的图层,在layers中定义数组中可用的图层
layers: [],
layers: [baiduMapLayer],
完整代码如下
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>openlayers叠加百度地图</title>
<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 {
margin: 0;
height: 100%;
width: 100%;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
/* 定义百度地图分辨率与瓦片网格 */
var resolutions = [];
for (var i = 0; i < 20; i++) {
resolutions[i] = Math.pow(2, 18 - i);
}
var tilegrid = new ol.tilegrid.TileGrid({
origin: [0, 0],
resolutions: resolutions,
tileSize: [256, 256],
});
var baiduMapLayer = new ol.layer.Tile({
title: '百度地图瓦片图',
source: new ol.source.TileImage({
projection: 'EPSG:3857',
tileGrid: tilegrid,
tilePixelRatio: devicePixelRatio,
tileUrlFunction: function (tileCoord, pixelRatio, proj) {
if (!tileCoord) {
return '';
}
var z = tileCoord[0];
var x = tileCoord[1];
var y = -tileCoord[2] - 1;
if (x < 0) {
x = 'M' + (-x);
}
if (y < 0) {
y = 'M' + (-y);
}
return 'https://maponline0.bdimg.com/tile/?qt=vtile&x=' + x + '&y=' + y + '&z=' + z + '&styles=pl&scaler=1&udt=20210730&from=jsapi3_0';
}
})
});
var map = new ol.Map({
layers: [baiduMapLayer],
view: new ol.View({
center: [12958111.00024869, 4827211.77706951],
projection: 'EPSG:3857',
zoom: 10,
}),
target: 'map'
});
</script>
</body>
</html>
注:底图要与数据坐标系一致。 百度互联网底图坐标系是BD09,若底图采用百度互联网底图,相应的上图绘制点线面时,坐标系也要采用BD09坐标系,才能保证图层不偏移。