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:
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!