修改于2021/1/17
公共地圖資源基本都是全國(guó)范圍或者全球范圍數(shù)據(jù),但具體業(yè)務(wù)需求往往只是需要顯示局部范圍或者局部高亮顯示。本案例基于Openlayers實(shí)現(xiàn)世界地圖內(nèi)蒙古區(qū)域的局部顯示以及呼倫貝爾、阿榮旗的高亮顯示。
1、地圖局部顯示
- 加載天地圖影像圖層、道路中文注記圖層。
- 道路中文注記圖層渲染后根據(jù)內(nèi)蒙古邊界范圍進(jìn)行局部裁剪。此處使用canvas的復(fù)合操作(globalCompositeOperation),在源圖像中顯示目標(biāo)圖像(destination-in)。

- 示例代碼
layer.on("postrender", function (e) {
let vectorContext = getVectorContext(e);
e.context.globalCompositeOperation = 'destination-in';
// feature 為內(nèi)蒙古面要素
vectorContext.drawFeature(feature, new Style({
fill: new Fill({
color: 'black',// 必需設(shè)置顏色
})
}));
e.context.globalCompositeOperation = 'source-over';
});
2、地圖局部高亮
- 創(chuàng)建新的畫布,大小與當(dāng)前視圖窗口大小一致。
- 新的畫布填充陰影圖形。
- 根據(jù)呼倫貝爾或阿榮旗邊界坐標(biāo),在新畫布上繪制區(qū)域圖形。
- 新畫布中顯示區(qū)域圖形外的陰影圖形,即區(qū)域圖形透明顯示。
- 將新畫布圖形填充到地圖圖層畫布上。

- 示例代碼
//points: 呼倫貝爾或阿榮旗邊界坐標(biāo)
//ctx:地圖圖層畫布
heightLight(points, ctx) {
let canvas = ctx.canvas;
let onePageCanvas = document.createElement('canvas');
onePageCanvas.setAttribute('width', String(canvas.width));
onePageCanvas.setAttribute('height', String(canvas.height));
let ctx_ = onePageCanvas.getContext('2d');
ctx_.rect(0, 0, canvas.width, canvas.height);
ctx_.fillStyle = "rgba(3,24,51,0.60)";
ctx_.fill();
ctx_.globalCompositeOperation = 'destination-out';
ctx_.beginPath();
for (let i = 0, cout = coords.length; i < cout; i++) {
// 獲取屏幕坐標(biāo)
let screenCoord = this.map.getPixelFromCoordinate(coords[i]);
let x = screenCoord[0];
let y = screenCoord[1];
if (i === 0) {
ctx_.moveTo(x, y);
} else {
ctx_.lineTo(x, y);
ctx_.lineTo(x, y);
}
}
ctx_.closePath();
ctx_.fill();
let patten = ctx.createPattern(onePageCanvas, "no-repeat");
ctx.fillStyle = patten;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}