Openlayers:添加纯色图层作为覆盖

问题描述

我想提供两个点(GPS坐标)作为输入(例如,左上角和右下角),并添加一个仅此区域完全可见的图层。其余应填充有纯色和半透明。应该看起来像这样:

enter image description here

我是Openlayers的新手,无法找到示例...我发现此示例添加了叠加层,但在这里并没有真正的帮助: https://openlayers.org/en/latest/examples/overlay.html

是否需要使用库的哪个函数/部分?

解决方法

您可以定义一个覆盖视图范围的多边形,并在指定范围内带有孔。然后将其显示在基本层向量上下文中

import "ol/ol.css";
import Map from "ol/Map";
import OSM from "ol/source/OSM";
import TileLayer from "ol/layer/Tile";
import View from "ol/View";
import { fromLonLat,transformExtent } from "ol/proj";
import { getVectorContext } from "ol/render";
import { fromExtent } from "ol/geom/Polygon";
import { Style,Fill } from "ol/style";

var extent = transformExtent([10,53,20,57],"EPSG:4326","EPSG:3857");

var osmLayer = new TileLayer({
  source: new OSM()
});

osmLayer.on("postrender",function (event) {
  var vectorContext = getVectorContext(event);
  vectorContext.setStyle(
    new Style({
      fill: new Fill({
        color: "rgba(0,255,0.25)"
      })
    })
  );
  var polygon = fromExtent(map.getView().getProjection().getExtent());
  polygon.appendLinearRing(fromExtent(extent).getLinearRing(0));
  vectorContext.drawGeometry(polygon);
});

var map = new Map({
  layers: [osmLayer],target: "map",view: new View({
    center: fromLonLat([15,55]),zoom: 5
  })
});

https://codesandbox.io/s/crazy-sun-qnezt?file=/main.js

或在基础层上方的单独矢量层中

var polygon = fromExtent(map.getView().getProjection().getExtent());
polygon.appendLinearRing(fromExtent(extent).getLinearRing(0));
var feature = new Feature({geometry: polygon});

var vectorLayer = new VectorLayer({
  source: new VectorSource({
    feature: [feature]
  }),style: new Style({
    fill: new Fill({
      color: "rgba(0,0.25)"
    })
  })
});

map.addLayer(vectorLayer);