简体   繁体   中英

Callback on clicking a layer in Open Layer

I have an Open Map that I created, with a vector layer with several polygons. How can I detect a user click on these polygons, and detect which square was clicked?

      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
    })
  });

Here is the jsfiddle

You can identify features by name or other property when clicking as in this example https://openlayers.org/en/latest/examples/vector-layer.html

The easiest way to name your polygons would be to use the minPoint and maxPoint. It is also simpler to create a polygon from an extent

  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;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM