openlayers6加载百度地图偏移问题解决
目录
功能说明
openlayers升级到6版本后,3、4、5版本加载百度地图的代码,加载的地图发生了偏移,原始代码和偏移情况如下
let baiduSource = new TileImage({
projection: projection,
tileGrid: tilegrid,
tileUrlFunction: function (tileCoord, pixelRatio, proj) {
if (!tileCoord) {
return '';
}
let z = tileCoord[0];
let x = tileCoord[1];
let y = tileCoord[2];
return "http://online1.map.bdimg.com/onlinelabel/?qt=tile&x=" +
x + "&y=" + y + "&z=" + z +
"&styles=pl&scaler=1&udt=20191119";
},
crossOrigin: 'anonymous'
});
解决方案
修改tileUrlFunction方法
let z = tileCoord[0];
let x = tileCoord[1];
let y = tileCoord[2];
修改为
let z = tileCoord[0];
let x = tileCoord[1];
let y = -tileCoord[2]-1;
原理
官网版本升级变化说明
https://github.com/openlayers/openlayers/releases/tag/v6.0.0
New internal tile coordinates
Previously, the internal tile coordinates used in the library had an unusual row order – the origin of the tile coordinate system was at the top left as expected, but the rows increased upwards. This meant that all tile coordinates within a tile grid’s extent had negative y
values.
Now, the internal tile coordinates used in the library have the same row order as standard (e.g. XYZ) tile coordinates. The origin is at the top left (as before), and rows or y
values increase downward. So the top left tile of a tile grid is now 0, 0
, whereas it was 0, -1
before.
x, y values for tile coordinates
origin
*__________________________
| | | |
| 0, 0 | 1, 0 | 2, 0 |
|________|________|________|
| | | |
| 0, 1 | 1, 1 | 2, 1 |
|________|________|________|
| | | |
| 0, 2 | 1, 2 | 2, 2 |
|________|________|________|
This change should only affect you if you were using a custom tileLoadFunction
or tileUrlFunction
. For example, if you used to have a tileUrlFunction
that looked like this:
// before function tileUrlFunction(tileCoord) { const z = tileCoord[0]; const x = tileCoord[1]; const y = -tileCoord[2] - 1; // do something with z, x, y }
You would now do something like this:
// after function tileUrlFunction(tileCoord) { const z = tileCoord[0]; const x = tileCoord[1]; const y = tileCoord[2]; // do something with z, x, y }