[GIS] Openlayers 5: Click event on specific layer

openlayers

I have a couple of layers and i want to add click event on a specific layer of the map.

E.g. If clicking on parcels, do different ajax request than clicking on buildings.

How can i do it?

    var wmsLayer = new ol.layer.Image({
  source: wmsSource
});
var map = new ol.Map({
  target: 'map',
  layers: [baseLayer, wmsLayer],
  view: new ol.View({
    center: ol.proj.fromLonLat([33.33386, 35.14710]),
    zoom: 14
  })
});

map.on('click', function (evt) {
  map.forEachLayerAtPixel(evt.pixel, function (layer) {
    if (layer==='web:Parcels') {
      console.log('parcels clicked');
    }
  });
});

Best Answer

You can add and retrieve extra attributes on a layer and aren't limited by key names. Here's a sample for OpenStreetMaps:

var baseLayer = new ol.layer.Tile({
        id: 'base_osm',
        title: 'OpenStreetMap',
        group: 'base',
        whatever: 'Testing 123',
        visible: true,
        source: new ol.source.OSM(),
})

map.on('singleclick', function (evt) {
    map.forEachLayerAtPixel(evt.pixel, function(layer) {
        console.log(evt.pixel);
        console.log(layer);
        var id = layer.get('title');
        console.log(id);
        var title = layer.get('title');
        console.log(title);
        var whatever = layer.get('whatever');
        console.log(whatever);
    });
});

See https://openlayers.org/en/latest/apidoc/module-ol_layer_Base-BaseLayer.html#get for the API Doc on this.

That should plug right into a WMS example and a working fiddle is at https://jsfiddle.net/ategenkamp/Lhekcvna/3/ as well based on https://openlayers.org/en/v4.6.5/examples/wms-tiled.html

Let me know if that helps!

Related Question