Search code examples
javascriptopenlayers-3

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


Solution

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