[GIS] How to several vector layers have different controls, using Openlayers

javascriptlineopenlayers-2point

Using openlayers I have two vector layers. One layer is called lineLayer consisting of vector lines, and the other is called pointLayer consisting of points. When I hover on the lines I want to be able to highlight the line, and identify the vector object when I click on it. When I hover on the point I want to highlight the point and be able to drag it. My code works separately for lines and points, but not when I put it together.

This is how I manage the line layer:

// handle interactions with lines
var highlightCtrl = new OpenLayers.Control.SelectFeature(lineLayer, {
    hover: true,
    highlightOnly: true,            
    renderIntent: "temporary"
});

map.addControl(highlightCtrl);
highlightCtrl.activate();

var selectCtrl = new OpenLayers.Control.SelectFeature(lineLayer, {      
    clickout: true, 
    onSelect: function(feature){console.log(feature)}       
});

map.addControl(selectCtrl);         
selectCtrl.activate();

And this is how I manage the points:

// handle interactions with points 
var highlightpoint = new OpenLayers.Control.SelectFeature(pointLayer, {
    hover: true,
    highlightOnly: true,
    renderIntent: "temporary",
});

map.addControl(highlightpoint);
highlightpoint.activate();

var dragStart = new OpenLayers.Control.DragFeature(pointLayer, {
    autoActivate: true
}); 

map.addControl(dragStart);
dragStart.activate();

From reading other examples I have noticed that the order seems to matter when a control is added. However, I've tried all the possible combinations of layer adding, and it does not seem to make a difference.

Is there some way to do this that I am overlooking?

Best Answer

You can pass an array of layers to the select control

selectControl = new OpenLayers.Control.SelectFeature(
    [lineLayer, pointLayer],
    {
        clickout: true, toggle: false,
        multiple: false, hover: false,
        toggleKey: "ctrlKey", // ctrl key removes from selection
        multipleKey: "shiftKey" // shift key adds to selection
    }
);

map.addControl(selectControl);
selectControl.activate();

See the openlayers documentation

To add different behavior for each layer, you could use the "featureselected" and "featureunselected" like in this example

EDIT

How to handle both click and hover control? I didn't try, but following this example should be done easily. Notice that the "hover" control is nothing else that a select control with 'hover': true. So, just add another control passing to it the array of layers.