This sample shows how to use the hitTest() method on the Map component to access features in a VectorTileLayer. This is done by setting up a pointer-move event handler on the Map component and passing the returned x, y screen coordinates to the hit
method, along with additional options to only include graphics from the VectorTileLayer. The method returns a promise, resolving to an array of objects containing any features retrieved from the VectorTileLayer. Subsequently, the content is generated to include contours information and is presented in a tooltip.
// Listen to map component's pointer move event and call hittest
// Display the contours info if the hittest result
// contains contours information from vector tile layer
viewElement.addEventListener("arcgisViewPointerMove", async (event) => {
let hits;
try {
hits = await hitTest(event.detail);
if (hits) {
let displayContent;
for (let hit of hits) {
displayContent = hits.map((hit) => {
const styleLayer = layer.getStyleLayer(hit.graphic.origin.layerId);
const mapPoint = viewElement.toMap({ x: event.detail.x, y: event.detail.y });
graphic.geometry = mapPoint;
let depressionValue;
// check the values returned in depression attributes and assign descriptive info
switch (hit.graphic.attributes["DEPRESSION"]) {
case 0:
depressionValue = "Depression status is indeterminate";
break;
case 1:
depressionValue = "Depression contour";
break;
case 2:
depressionValue = "Feature is a normal contour";
break;
default:
depressionValue = hit.graphic.attributes["DEPRESSION"];
}
const content = {
Contour: hit.graphic.attributes["Contour"],
Depression: depressionValue,
Unit: hit.graphic.attributes["Unit"],
};
return content;
});
}
// clean up the tooltip content to show contours info
displayContent[0] = JSON.stringify(displayContent[0])?.replace(/[{}]/g, "");
displayContent[0] = displayContent[0].replace(/\"/g, "").replace(/:/g, ": ");
displayContent[0] = displayContent[0].split(",").join("<br />");
const screenPoint = hits.screenPoint;
vtlTooltip.show(screenPoint, displayContent[0]);
} else {
vtlTooltip.hide();
}
} catch {}
});
The following snippet shows how the hit
method returns label features from a VectorTileLayer.
// debounce the hittest as user moves the mouse over the map to improve performance
const hitTest = promiseUtils.debounce(async (event) => {
// get hit test results only from the vector tile layer
const hit = await viewElement.hitTest(event, { include: layer });
if (hit.results.length) {
// check if the hit test results from the vector tile layer contains
// results for label layers defined in styleLayerIds
const results = hit.results.filter((result) => {
return result.graphic;
});
results.screenPoint = hit.screenPoint;
if (!results.length) {
return null;
}
return results;
} else {
return null;
}
});