Open Layer 中点击图层的回调

Callback on clicking a layer in Open Layer

我创建了一个开放地图,其中包含一个包含多个多边形的矢量图层。如何检测用户点击了这些多边形,并检测点击了哪个方块?

      var map = new Map({
    layers: [
      new TileLayer({
        source: new TileJSON({
          url: 'https://maps.siemens.com/styles/osm-bright.json'
        })
      }),
      new VectorLayer({
        source: new VectorSource({
          features: polygonFeatures
        }),
        style: new Style({
          stroke: new Stroke({
            width: 1,
            color: [0, 0, 0, 1]
          }),
          fill: new Fill({
            color: [255, 0, 255, 0.3]
          })
        })
      })
    ],
    target: 'map',
    view: new View({
      center: midPoint,
      zoom: 6.1
    })
  });

这是jsfiddle

您可以按名称或其他 属性 来识别特征,如本例所示 https://openlayers.org/en/latest/examples/vector-layer.html

命名多边形的最简单方法是使用 minPoint 和 maxPoint。从范围

创建多边形也更简单
  function mapSquare(minPoint, maxPoint) {
    var extent = minPoint.concat(maxPoint);
    var polygonFeature = new Feature({
      geometry: Polygon.fromExtent(minPoint.concat(maxPoint)).transform('EPSG:4326','EPSG:3857'),
      name: extent.toString()
    });
    return polygonFeature;
  }