Automatically Querying All Your Layers In An ArcGIS JS Map

 

Cool feature in esri's ArcGIS JS API I only accidentally found out about is the hitTest function. what it lets you do is query all the layers under a specific point.

I encountered this function when answering these two quetions:

1. How to simulate/trigger a click on the map/view

2. One popup for multiple layers in ArcGIS JS API

    Either use case is cool on its own, simulating a click on the map can be very useful if what you want to do is create a video that simulates querying the map continuously at specific point, or that shows where points are added when they are added and what they intersect.

    The other use case will be to use one custom popup to show every thing under your mouse (click or hover), this can be helpful if you don't want to use esri's popup which is easily customizable with arcade expressions (fancy name for simple JS code) but for jsut one layer, using view.hitTest is useful for creating a popup summarizing all layers below.

    Since I don't use ArcGIS JS API at all, I had to use some sample code to test this out.This is the code sample I used - ArcGIS - 2 Layers 1 Popup

The code I added (before the last }); ) is this:


var hitResults=[]
var popupContent =''
view.on("click"function(event) {

    view.hitTest(event).then(function (response) {
        if (response.results.length) {

            for(var i=0;i<response.results.length;i++ ){

            hitResults.push([response.results[i].graphic.layer.title,
             
response.results[i].graphic.attributes])
            popupContent += `<b>${response.results[i].graphic.layer.title}</b>: 
${
response.results[i].graphic.attributes['objectid']}<br>`
            }  

            view.popup.autoOpenEnabled = false;

            view.popup.open({
            // Set the popup's title to the coordinates of the location
            title: "multiple layer results",
            location: event.mapPoint,
            content: popupContent
            });
        }
    })
});


That was just a proof of concept, you can obviously customize the popup a lot further and also removing results for basemap (in this case a vector tiles one) layers.

You can see the result in the image at the start of the post.

Comments