概述
前面有两篇文章分别介绍了矢量数据点和线、面的实现,本文讲讲静态图片的绘制和WMS服务的展示。
4.绘制图片
图片的绘制我们分两种:静态图片和WMS服务。
4.1 静态图片
绘制静态图片我们只需要两个参数:图片地址和图片四至。实现代码如下:
代码语言:javascript复制/**
* 绘制静态图片
* @private
*/
ImageLayer.prototype._drawStaticImage = function () {
const that = this;
const extent = that._params.extent;
const url = that._params.url;
const pixelMin = that._map2pixel([extent[0], extent[1]]);
const pixelMax = that._map2pixel([extent[2], extent[3]]);
const width = Math.abs(pixelMax.x - pixelMin.x);
const height = Math.abs(pixelMax.y - pixelMin.y);
const img = new Image();
img.src = url;
img.onload = function () {
that._ctx.drawImage(img, pixelMin.x, pixelMax.y, width, height);
}
}
实现后效果如下:
4.2绘制WMS服务
一个wms服务的请求应包括以下参数:
代码语言:javascript复制{
SERVICE: 'WMS',
REQUEST: 'GetMap',
FORMAT: 'image/png',
TRANSPARENT: true,
LAYERS: that._params.layer,
SRS: 'EPSG:3857',
WIDTH: width,
HEIGHT: height,
BBOX: projMin.concat(projMax).join(',')
}
一个完整的wms
的请求地址如:http://localhost:8081/geoserver/lzugis/wms?SERVICE=WMS&REQUEST=GetMap&FORMAT=image/png&TRANSPARENT=true&LAYERS=lzugis:china_prov_people&SRS=EPSG:3857&WIDTH=1920&HEIGHT=969&BBOX=5721121.240344884,1414403.022565099,17727742.969104737,7473994.926298538。wms的实现方式如下:
/**
* 绘制wms服务
* @private
*/
ImageLayer.prototype._drawWmsImage = function () {
const that = this;
let extent = that._map.getBounds().toArray();
extent = extent[0].concat(extent[1]);
// 超范围处理
const xmin = extent[0] < -180 ? -180 : extent[0];
const ymin = extent[1] < -90 ? -90 : extent[1];
const xmax = extent[2] > 180 ? 180 : extent[2];
const ymax = extent[3] > 90 ? 90 : extent[3];
const pixelMin = that._map2pixel([xmin, ymin]);
const pixelMax = that._map2pixel([xmax, ymax]);
const width = Math.round(Math.abs(pixelMax.x - pixelMin.x));
const height = Math.round(Math.abs(pixelMax.y - pixelMin.y));
const projMin = turf.projection.toMercator([xmin, ymin]);
const projMax = turf.projection.toMercator([xmax, ymax]);
const wmsParams = {
SERVICE: 'WMS',
REQUEST: 'GetMap',
FORMAT: 'image/png',
TRANSPARENT: true,
LAYERS: that._params.layer,
SRS: 'EPSG:3857',
WIDTH: width,
HEIGHT: height,
BBOX: projMin.concat(projMax).join(',')
};
let url = that._params.url;
for(const key in wmsParams) {
const join = url.indexOf('wms?') !== -1
? '&'
: '?';
url = `${join}${key}=${wmsParams[key]}`;
}
const img = new Image();
img.src = url;
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function () {
that._ctx.drawImage(img, pixelMin.x, pixelMax.y, width, height);
}
}
实现后效果如下: