How do you listen for mouse clicks on graphics in a graphics layer in 4.0? I can listen for mouse clicks on a view, but how do I know which graphic element was clicked on if any?
Solved! Go to Solution.
You'll want to use the view.hitTest method to get graphics in the View.
view.on("click", function(event) { view.hitTest(event.screenPoint).then(function(response) { var graphics = response.results; graphics.forEach(function(graphic) { console.log(graphic); }); }); });
The benefit here over how you would have done it in 3.x is that in 3.x you would only get the top-most graphic that was clicked. Now you'll get any graphics under the location where you clicked by using the hitTest.
You can also look at this sample.
You'll want to use the view.hitTest method to get graphics in the View.
view.on("click", function(event) { view.hitTest(event.screenPoint).then(function(response) { var graphics = response.results; graphics.forEach(function(graphic) { console.log(graphic); }); }); });
The benefit here over how you would have done it in 3.x is that in 3.x you would only get the top-most graphic that was clicked. Now you'll get any graphics under the location where you clicked by using the hitTest.
You can also look at this sample.
Thank you!
Hello Rene Rubalcava,
This doesn't seem to be working properly as far as I can tell. When I add 'console.log(response);' on line 129 to the Sandbox example I only get the top-most graphic wherever I click, and not all graphics like you suggested. The same holds for this hitTest example.
I encounter the same problem in my own project, running the 4.0 API. The hitTest does return the top-most graphic for each layer under the click, but never multiple graphics from a single layer. Do you know how to fix this? Or am I doing something wrong?
Kind regards,
Björn
Sorry, I should have clarified earlier. It's only going to return one graphic per layer. This is because it would get expensive to try and recurse over the SVG to find overlapping features. If this changes in the future, I'll update here.
what about mouseover??
The View doesn't have a mouseover event at this time. You could try listening for mouseover on the View container.
Another question on the graphics object.
How can we use 4.0 library (For example: Get started with graphics | ArcGIS API for JavaScript 4.0 ) to draw the graphic in the map(Although the x,y value of the point/polyline/polygon can be found in the object)? is there any better way to do it?