Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

OpenLayers Feature Highlighting on Mouse Hover

Tech 1

Highlighting vector features when the cursor passes over them can be achieved through two distinct mechanisms in OpenLayers.

Method 1: Built-in Select Interaction

The Select interaction can be configured to trigger on cursor movement rather than a click by specifying the pointerMove condition.

const hoverInteraction = new ol.interaction.Select({
  condition: ol.events.condition.pointerMove,
  hitTolerance: 2
});
map.addInteraction(hoverInteraction);

To react to the selection changes, listen to the select event:

hoverInteraction.on('select', (evt) => {
  const chosenFeatures = evt.selected;
  if (chosenFeatures.length > 0) {
    console.log('Feature entered:', chosenFeatures);
  } else {
    console.log('Feature exited');
  }
});

Method 2: Manual Pixel Detection and Styling

Instead of relying on the Select interaction, you can manual detect faetures at the cursor's pixel coordinates and apply styles directly.

const highlightAppearance = new ol.style.Style({
  fill: new ol.style.Fill({
    color: 'rgba(255, 100, 50, 0.7)'
  }),
  stroke: new ol.style.Stroke({
    color: 'darkred',
    width: 3
  }),
  image: new ol.style.Circle({
    radius: 8,
    fill: new ol.style.Fill({
      color: 'rgba(255, 100, 50, 0.7)'
    }),
    stroke: new ol.style.Stroke({
      color: 'darkred',
      width: 2
    })
  })
});

let currentlyHovered = null;

function processHoverEvent(mapEvent) {
  const targets = map.getFeaturesAtPixel(mapEvent.pixel, {
    hitTolerance: 4
  });

  if (targets && targets.length > 0) {
    const target = targets[0];
    if (currentlyHovered !== target) {
      if (currentlyHovered) currentlyHovered.setStyle(undefined);
      currentlyHovered = target;
      currentlyHovered.setStyle(highlightAppearance);
    }
  } else if (currentlyHovered) {
    currentlyHovered.setStyle(undefined);
    currentlyHovered = null;
  }
}

map.on('pointermove', processHoverEvent);

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.