Search code examples
angularopenlayersgeoserver

Use click event in Angular + Openlayers to detect the layer clicked


I need to know what layer I am clicking in an openlayers map to grab some data of it later.

I've made it before but only using one layer. Now I have more than one and I would like to know what layer I'm clicking to grab its information from geoserver.

capa1WMS:TileLayer;
map:Map;

...

getDatosCapaWMS(url:string): Observable<any>{
    return this.http.get(url);
}

clickMapa(event:any):void{
    if(this.capa1WMS.getSource()!=null){
      var url = this.capa1WMS.getSource().getGetFeatureInfoUrl(
        this.map.getEventCoordinate(event), this.view.getResolution(), this.view.getProjection(),
        {'INFO_FORMAT': 'application/json'});
      this.getDatosCapaWMS(url).subscribe(data => { 

        //stuff

    });
    }   
}  

And my HTML code

<div id="map" class="map" (click)="clickMapa($event)"></div>

I have seen that openlayers has a method called forEachFeatureAtPixel() but I haven't made it work


Solution

  • Ok, Mike gave the solution

    this.map.forEachLayerAtPixel(this.map.getEventPixel(event)) to get the layers to use for .getSource().getGetFeatureInfoUrl()