Access features with hitTest

This sample shows how to use the hittest method on the Map component to access features in a FeatureLayerView. This is done by setting up arcgisViewPointerDown and arcgisViewPointerMove event handlers on the map component and passing the returned screen x, y coordinates from the event payload to the hitTest() method of the map component. Additional options are provided to only include graphics from the FeatureLayerView. A promise is returned, which resolves to an array of objects containing any features from the FeatureLayerView. If a feature is returned, then the sample displays an information pertaining to this feature. It also highlights all features belonging to the same hurricane as the feature returned from the hitTest.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Set up an event handler for pointer-down (mobile) and pointer-move events
// and retrieve the screen x, y coordinates
arcgisMap.addEventListener("arcgisViewPointerDown", eventHandler);
arcgisMap.addEventListener("arcgisViewPointerMove", eventHandler);

async function eventHandler(event) {
  // only include graphics from hurricanes layer in the hitTest
  const opts = {
    include: layer
  }
  // the hitTest() checks to see if any graphics from the hurricanesLayer
  // intersect the x, y coordinates of the pointer
  const response = await arcgisMap.hitTest(event.detail, opts);
  if (!response.results.length) {
    // no results returned from hittest, remove previous highlights
    highlight?.remove();
    document.getElementById("info").innerHTML = setupHurricaneInfoDiv({NAME:"", CAT: "", WIND_KTS: ""});
    return;
  }

  // the topmost graphic from the hurricanes layer and display attribute
  // values from the graphic to the user
  const graphic = response.results[0].graphic;

  const attributes = graphic.attributes;
  const year = attributes.YEAR;
  const name = attributes.NAME;

  // update the hurricanes info div
  document.getElementById("info").innerHTML = setupHurricaneInfoDiv(attributes);

  // highlight all features belonging to the same hurricane as the feature
  // returned from the hitTest
  const query = layerView.createQuery();
  query.where = `YEAR = ${year} AND NAME = '${name}'`;
  layerView.queryObjectIds(query).then((ids) => {
    highlight?.remove();
    highlight = layerView.highlight(ids);
    currentYear = year;
    currentName = name;
  });
}

The sample displays hurricane paths. Click any line segment to view some of its attributes and assign the same symbol to all line segments with the same storm name.

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.