前言
之前参考openlyers3 示例锦集,发布百度瓦片地图,但是地图发生偏移,如图所示:
一直在网上查找相同问题,一直未解决。感觉是瓦片的排序出现了问题,于是自己尝试修改代码
if (y < 0) {
y = "M" + (-y);
}
修改成
if (y < 0) {
y = "M" + (y);
}
于是中国地图这一部分不发生偏移了,但其他地方还是有偏移。
最后解决
终于找到一篇博客,找到了原因,原来是百度地图的原点是在右下角,而ol的原点是在左上角,需要对瓦片标记进行翻转。
if (x < 0) {
x = "M" + (-x);
}
y = -y;
最终完美解决。
完整代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>加载百度地图</title>
<link href="v6.10.0/css/ol.css" rel="stylesheet" type="text/css" />
<script src="v6.10.0/build/ol.js" type="text/javascript"></script>
<style type="text/css">
#mapCon {
width: 100%;
height: 800px;
}
</style>
</head>
<body>
<div id="mapCon">
</div>
<script type="text/javascript">
//坐标参考系
var projection = ol.proj.get("EPSG:3857");
//分辨率
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: projection,
//设置分辨率
tileGrid: tilegrid,
//出图基地址
tileUrlFunction: function (tileCoord, pixelRatio, proj) {
if (!tileCoord) {
return "";
}
var z = tileCoord[0];
var x = tileCoord[1];
var y = tileCoord[2];
if (x < 0) {
x = "M" + (-x);
}
y = -y;
console.log(x,y,z)
return "http://online3.map.bdimg.com/onlinelabel/?qt=tile&x=" + x + "&y=" + y + "&z=" + z + "&styles=pl&udt=202301121&scaler=1&p=1";
}
});
//百度地图
var baidu_layer = new ol.layer.Tile({
source: baidu_source
});
//地图容器
var map = new ol.Map({
target: 'mapCon',
layers: [baidu_layer],
view: new ol.View({
center: ol.proj.transform([103.623897,34.469957], 'EPSG:4326', 'EPSG:3857'),
zoom: 4,
minZoom:3,
maxZoom: 16
})
});
</script>
</body>
</html>