[GIS] Combining Hover and Click events in OpenLayers

eventsopenlayers-2

I can specify event callbacks in an OpenLayers layer:

var vectorA=new OpenLayers.Layer.Vector("A");
vectorA.events.on({
  "featureselected": callback
});

and I can specify event callbacks in a control's constructor:

highlightControl = new OpenLayers.Control.SelectFeature(vectorA, {
  renderIntent: "temporary",
  hover: true,
  highlightOnly: true,
  eventListeners: {
    featurehighlighted: hoverFeatureCallback,
    featureunhighlighted: unhoverFeatureCallback
  }
});

Can I mix them properly?

Basically, one layer needs both select and hover events, so I'd have two controls, one that hovers, and give each their own callbacks (like the second example above.)

AND I have multiple layers that need select events, so in that case I'd define the events in the layers themselves, like the first example. However, I can't use the first example with hover and select because, in OL's infinite wisdom, hover events are really just select events.

How can I have two layers respond to hover events and one of them also respond to select events?

Best Answer

To combine hover and click in OpenLayers 2.x, it is sufficient to override the clickFeature method of OpenLayers.Control.SelectFeature. The default implementation does nothing on hover but is still called on click:

clickFeature: function (feature) {
  if (!this.hover) {
    ...
  }
}

This code demonstrates that it is possible to handle the feature click by overriding clickFeature:

var highlightCtrl = new OpenLayers.Control.SelectFeature([vectors, vectors2], 
{
  hover: true,
  onSelect: function (e) { ... process feature hover ...  }, 
  clickFeature: function (e) { alert("clicked feature: " + e.id); } 
});