[GIS] OpenLayers 2.12 + click handler + get the name of the vector

openlayers-2vector

Basically,

I add several vector layers (KML content got from jQuery GET) in this way:

var layer1Vector= new OpenLayers.Layer.Vector('activeInfo');
layer1Vector.addFeatures(featuresLayer1Vector);
mp.addLayer(layer1Vector);

It works quite well.

Instead of adding the

selectControlKml = new OpenLayers.Control.SelectFeature(
    [layer1, layer2, ***], {
        clickout: true, toggle: false,
        multiple: false, hover: false,
        toggleKey: 'ctrlKey',
        multipleKey: 'shiftKey'
    }
);

I knew that it's possible to add a "general" click handler event

OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
    defaultHandlerOptions:{
        'single': true,
        'double': false,
        'pixelTolerance': 5,
        'stopSingle': true,
        'stopDouble': false,
        'delay': 0
    },  
    initialize: function(options) {
        this.handlerOptions = OpenLayers.Util.extend({}, this.defaultHandlerOptions);
        OpenLayers.Control.prototype.initialize.apply(this, arguments); 
        this.handler = new OpenLayers.Handler.Click(
            this, {'click': this.trigger}, 
            this.handlerOptions
        );
    },
    trigger: function(e) {

        if (e.target._featureId) {
            //var feature = vectorLayer.getFeatureById(e.target._featureId);
            alert('click on fea' + e.target._featureId)
            //$(e.target).css('fill', '#000000');
            //$(e.target).css('cursor', 'wait');
            //$("div#info").append("<span>You just clicked on " + feature.id + "<span><br />");
        }
***   

If I click on a vector layer I have to open different custom popups (qTip2). The code:

if (e.target._featureId) {

works, but how can I get the layer name based on the e object? I analyzed all the methods/properties, but without having success.

E.g.
One of my layers was defined as:

var layer1Vector= new OpenLayers.Layer.Vector('activeInfo');

I need to get 'activeInfo'.

Thanks a lot!

Best Answer

Since this is the vector in this context... this.name will give you "activeInfo".

...
trigger: function(e) {

        alert(this.name);
        if (e.target._featureId) {
...

here's my console.log(this) within trigger function.

enter image description here

UPDATE PER Comment

So your problem is that you're trying to assign the click handler before the layer has been created.

This Works. Here I have moved the call to the addControls(vectorLayer) function after you add the layer. This works fine. Notice I've added a layer parameter. This will make it easy for you when you're adding and removing layers.

Once you remove a vector Layer the handler is gone with it. If you add another layer, simply call the addControls(yourNewLayerName) function to add the handler to the new layer.