Openlayers:添加纯色层作为叠加层

Openlayers: Add a solid coloured layer as overlay

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

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

知道需要使用库的哪个函数/部分吗?

您可以定义一个覆盖视图范围的多边形,并为您指定的范围设置一个洞。然后在base layers vector context

中显示
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, 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, 255, 255, 0.25)"
    })
  })
});

map.addLayer(vectorLayer);