概述
前面已经有三篇文章分别讲述了点、线和面、图片的绘制,在本文讲讲如何实现切片的绘制。
5. 绘制切片
前面的文章地图切片提到了切片的几个重要参数:切片范围、切片原点、分辨率,这些概念在实现切片的调用的时候都会用到,下面为实现代码:
/**
* 在地图上展示切片
* @private
*/
TileLayer.prototype._showTile2Map = function () {
const that = this;
let extent = that._map.getBounds().toArray();
const projMin = turf.projection.toMercator(extent[0]);
const projMax = turf.projection.toMercator(extent[1]);
const zoom = Math.ceil(that._map.getZoom());
const res = that._tileParams.zoomRes[zoom];
const tileSize = this._params.tileSize || 256;
const xmin = Math.floor((projMin[0] - that._tileParams.tileStart[0]) / (res * tileSize));
const xmax = Math.ceil((projMax[0] - that._tileParams.tileStart[0]) / (res * tileSize));
const ymin = Math.floor((that._tileParams.tileStart[1] - projMax[1]) / (res * tileSize));
const ymax = Math.ceil((that._tileParams.tileStart[1] - projMin[1]) / (res * tileSize));
for (let x = xmin; x <= xmax; x++) {
for (let y = ymin; y <= ymax; y++) {
that._addTile2Map(x, y, zoom);
}
}
}
/**
* 展示单个切片
* @param x
* @param y
* @param z
* @private
*/
TileLayer.prototype._addTile2Map = function (x, y, z) {
const that = this;
const tileSize = that._params.tileSize || 256;
const res = that._tileParams.zoomRes[z];
const xmin = that._tileParams.tileStart[0] + x * (res * tileSize);
const xmax = that._tileParams.tileStart[0] + (x + 1) * (res * tileSize);
const ymax = that._tileParams.tileStart[1] - y * (res * tileSize);
const ymin = that._tileParams.tileStart[1] - (y + 1) * (res * tileSize);
const min = turf.projection.toWgs84([xmin, ymin]);
const max = turf.projection.toWgs84([xmax, ymax]);
const pixelMin = that._map2pixel(min);
const pixelMax = that._map2pixel(max);
const width = Math.abs(pixelMax.x - pixelMin.x);
const height = Math.abs(pixelMax.y - pixelMin.y);
let url = that._params.url;
url = url.replace('{x}', x);
url = url.replace('{y}', y);
url = url.replace('{z}', z);
const img = new Image();
img.src = url;
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function () {
that._ctx.drawImage(img, pixelMin.x, pixelMax.y, width, height);
}
}
/**
* 初始化切片参数
* @private
*/
TileLayer.prototype._initTileParams = function () {
const minZoom = 0;
const maxZoom = 18;
const originExtent = [-20037508.34, -20037508.34, 20037508.34, 20037508.34];
const tileSize = this._params.tileSize || 256;
let tileParams = {
originExtent: originExtent,
tileStart: [originExtent[0], originExtent[3]],
zoomRes: {}
};
for(let i = minZoom; i <= maxZoom; i++) {
const res0 = (originExtent[2] - originExtent[0]) / tileSize;
tileParams.zoomRes[i] = res0 / Math.pow(2, i);
}
this._tileParams = tileParams;
}
上面的代码中_initTileParams
是以标准的谷歌切片的参数。切片调用的是谷歌的标注图层,实现后的效果如下: