Search code examples
openlayersmouse

How can I detect a mousewheel click in Openlayers 8.2?


So I have built a map application where I can see my photos on a map. I'm using OpenLayers 8.2 to display the map. I have made a click event when the user clicks a thumbnail on the map to show the complete photo, like this:

map.on('singleclick', function(evt) {
    var feature = map.forEachFeatureAtPixel(evt.pixel, function(feature, layer) {
        return feature;
        });
    if (feature) {
        newLink = link.replace('%2Areplace%2Ame%2A', feature.get("seq"));
        window.location.href = newLink;
    }
});

But now I would like to capture the middle mouse button (mouse wheel) click so I can have the user open the photo in a new tab. I can't seem to find out how that works. I can handle right-clicks, touch events, double clicks, even the scrolling of the mouse wheel, but not the clicking.


Solution

  • You could register an event listener on the target html element like this:

    map.getTargetElement().addEventListener('mousedown', (event) => {
        if (event.button === 1) {
            const pixel = map.getEventPixel(event);
            const features = map.getFeaturesAtPixel(pixel);
            console.log('features:', features);
        }
    
        if (event.button === 0) {
            console.log('left');
        }
    
        if (event.button === 2) {
            console.log('right');
        }
    });