How can I detect a mousewheel click in Openlayers 8.2?

80 views Asked by At

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.

2

There are 2 answers

2
BR75 On BEST ANSWER

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');
    }
});
0
user23437660 On

As indicated by @BR75, this ended up being the solution:

map.getTargetElement().addEventListener('mousedown', (event) => {
    const pixel = map.getEventPixel(event);
    const features = map.getFeaturesAtPixel(pixel);
    newLink = link.replace('%2Areplace%2Ame%2A', features[0].get("seq"));
    if (event.button === 1) {
        // middle mouse button pressed
        window.open(newLink,'_blank');
    }
    if (event.button === 0) {
        // left mouse button pressed
        window.location.href = newLink;
    }
});