Accessing vector features by clicking in close proximity to, but not directly on, a vector in OpenLayers

I'm working with an Open Street Map that includes vectors (lines) displaying on the roads. Currently, I can only retrieve information about a vector by clicking directly on its pixels. Is there a way to make it so that I can click near the vector (a few pixels off) and still get the relevant information, in order to be less precise?

Code:

Here is the code snippet I am using to get features when I click on a vector:

var displayFeatureInfo  = function (pixel, coordinate) {
            var features = [];
            map.forEachFeatureAtPixel(pixel, function (feature, layer) {
                features.push(feature); // Storing each feature found in an array
            });

            if (features.length > 0) {   // If there are one or more features
                $("#popup").html('<object data=' + "http://URLToLoadDataFrom '/>'); // Loading data via jQuery
                popup.setPositioning('top-left');
                popup.setPosition(coordinate);
                container.style.display = 'block';
            } else {
                container.style.display = 'none';
            }                          

        };

        map.on('click', function (evt) {
            var coordinate = evt.coordinate;
            displayFeatureInfo(evt.pixel, coordinate);    
        });

Thanks for any help in advance.

Answer №1

You have the option to create an extent using the provided pixel and base your feature selection on the extent rather than a single point. This means utilizing the

vector.getSource().forEachFeatureIntersectingExtent
method instead of map.forEachFeatureAtPixel.

Take a look at this (sample here):

var displayFeatureInfo  = function (pixel, coordinate) {
            var features = [];
            //adjust this offset in pixels as needed
            var pixelOffSet = 5; 
            var pixelWithOffsetMin = [pixel[0]-pixelOffSet,pixel[1]+pixelOffSet];
            var pixelWithOffsetMax = [pixel[0]+pixelOffSet,pixel[1]-pixelOffSet];
            var XYMin =map.getCoordinateFromPixel(pixelWithOffsetMin)
            var XYMax =map.getCoordinateFromPixel(pixelWithOffsetMax)
            var extent = XYMax.concat(XYMin);
            var extentFeat= new ol.Feature(new ol.geom.Polygon([[
            [extent[0],extent[1]],
            [extent[0],extent[3]],
            [extent[2],extent[3]],
            [extent[2],extent[1]],
            [extent[0],extent[1]]
            ]]));   

            vector.getSource().forEachFeatureIntersectingExtent(extentFeat.getGeometry().getExtent(), 
            function (feature) {
                features.push(feature); // Adds each found feature to the array
            });

            if (features.length > 0) {   // If there are one or more features
                console.log("Features found when clicked on offset",features)
               // container.style.display = 'block';
            } else {
              console.log("No features found when clicking on offset")
            }                          

        };

        map.on('click', function (evt) {
            var coordinate = evt.coordinate;
            displayFeatureInfo(evt.pixel, coordinate);    
        });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method to define YAML array indices in JavaScript?

I apologize for my previous post. I have successfully integrated a RapidAPI for Covid-19 updates, which is now outputting the results as an array JSON in the console. You can view the YAML Array Output here. I am now facing a challenge in listing specifi ...

Utilizing properties from the same object based on certain conditions

Here's a perplexing query that's been on my mind lately. I have this object with all the styles I need to apply to an element in my React app. const LinkStyle = { textDecoration : 'none', color : 'rgba(58, 62, 65, 1)', ...

Responsive design with Flexbox, interactive graphics using canvas, and dynamic content resizing

I'm having difficulties with my canvas-based application. I have multiple canvases, each wrapped in a div container alongside other content. These containers are then wrapped in an "hbox" container. The objective is to create a dynamic grid of canvas ...

Utilize the native HTML attribute to capture the mouse wheel event

I'm interested in utilizing the mousewheel event in my project, but all the information I've found online relies on addEventListener(). I want to detect it using native HTML and CSS. In simpler terms, I'm hoping for something along the lines ...

Is there a way to share the Username and Password without the need to manually input it?

My goal is to develop a C++ application for my classmates at school. Currently, they are required to visit our school's website and navigate to the login page. Once there, they enter their username and password, log in, and proceed to find their spec ...

Scrolling with jQuery to create a fixed navigation bar

I'm having an issue with my navbar on my website. I used CSS and jQuery to keep it fixed at the top, but now when I click on a menu item, it doesn't scroll to that section of the page. Can anyone help me troubleshoot this problem? ...

What is the process to set up a WebSocket on Tornado for a production server rather than on a local machine?

Recently, I've delved into the world of WebSockets but have only experimented with them in a localhost environment while developing locally. Following this informative tutorial on real-time data visualization: https://medium.com/@benjaminmbrown/real-t ...

Optimizing the way JavaScript is incorporated into Django templates for maximum efficiency

Before, I followed this structure in a template <html> ... <script> {% include "myapp/includes/jquery-1.7.1.min.js" %} {% include "myapp/includes/myscript.js" %} </script> ... However, this resulted in all the JavaScript code being vis ...

Requesting an API token through the body using Javascript's Fetch function

I'm currently working on developing a frontend application using Javascript Fetch to interact with an API service. One of the tasks I need to accomplish is to create a token by using the POST method and sending an apiKey parameter in the Body. Once I ...

Every time I try to run npm start on my React app, I keep receiving the error message "? Something is already running on port 3000"

Whenever I try to start my React server, I keep receiving the message "? Something is already running on port 3000" in my terminal. Strangely, there is nothing actually running on port 3000. Here are the steps I have taken to try and solve this issue: Re ...

Creating a serial number in a Class without relying on a global variable is a useful technique that

I am looking for a way to assign a unique ID to each instance of a Class without relying on global variables. I have tried using a global variable and incrementing it, but I would prefer a more efficient approach. Is there a way to generate an ID within t ...

What could be preventing the background color from changing when attempting to use style.backgroundColor?

My objective is to store the current tab background color in a variable and then use that variable to change the body color. However, for some reason it is not working as expected. Can you help me figure out why? const tabName = 'someId'; var ...

MANDATORY activation of CONFIRMATION

Hello everyone, I'm seeking assistance with my code. Below is the form code I need help with: <form action="input.php" method="POST"> <input type="text" class="input" name="firstname" placeholder="First Name" required> <input t ...

Clicking to close tabs

I am currently working on implementing a tab functionality on my website and I want these tabs to be responsive. Here is the code snippet I have been using: function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.ge ...

Why will the experimental activation of React concurrent features in Nextjs 12 disable API routes?

I just upgraded to Next.js version 12 and set up some API routes (e.g. "/api/products"). These routes were functioning properly, but when I enabled concurrentFeatures: true in my next.config.ts, the API routes stopped working. The console display ...

I'm looking to fill multiple input boxes with the same value

I am looking to pass the same value to multiple input boxes. Currently, the script below only displays in one box but I want to display the main box result in all multiple input boxes. <script type='text/javascript' src='http://code.jque ...

Running into difficulties while attempting to sort through an object utilizing an array

My task is to filter a collection of objects based on an array of Fids. I have an object, $target = $('#tableA tr[data-id="' + elm.id + '"]'); // Collection of tr And I also have an array, var fids = $("#tableB tr .New.selected").pa ...

The JQuery library seems to be unresponsive on my webpage, despite being correctly included

Despite trying multiple ways to include the JQuery library on my page, I keep encountering the "$ is not defined" error. I have ensured that all the links were correct and from various sources, both local and external. What other options should I consider ...

Retrieval is effective in specific situations but ineffective in others

I have encountered an issue with fetching data only when using the async behavior. I am currently in the process of re-building a property booking website that was originally developed using Laravel and a self-built API. The new version is being created wi ...

Vue - Passing a parent's ref to a child component as a prop

Is there a way to pass the current component's reference to a child component in Vue.js? <template> <div class="screen" ref="screen"> <child-component :screenRef="screenRef"> </child-component> </div ...