### Start Development Server Source: https://github.com/esri/jsapi-resources/blob/main/layouts/dashboard-sample/README.md Start the development server to run the application locally. ```bash npm run dev ``` -------------------------------- ### Install Dependencies Source: https://github.com/esri/jsapi-resources/blob/main/layouts/dashboard-sample/README.md Install project dependencies using npm. ```bash npm i ``` -------------------------------- ### Load WebMap Server-Side in Node.js Source: https://context7.com/esri/jsapi-resources/llms.txt This example demonstrates loading a WebMap in a Node.js environment for server-side access to its metadata. It disables the IdentityManager as there is no DOM available and shows how to configure a local asset path if needed. This is useful for applications that need to read WebMap properties without rendering a map. ```javascript // templates/js-maps-sdk-node/webmap.js — load a WebMap server-side import WebMap from "@arcgis/core/WebMap.js"; import esriConfig from "@arcgis/core/config.js"; // Disable IdentityManager (no DOM available in Node.js) esriConfig.request.useIdentity = false; const webmap = new WebMap({ portalItem: { id: "3d52817a120b477db912add2e62ef9b6" } }); await webmap.load(); console.log(webmap.portalItem.description); // Configure local asset path if needed esriConfig.assetsPath = "https://mywebsite.com/assets"; ``` -------------------------------- ### Scaffold a New Application with Vite Template Source: https://github.com/esri/jsapi-resources/blob/main/templates/js-maps-sdk-vite/README.md Use this command to quickly create a new ArcGIS application using the Vite TypeScript template. Ensure you have npx installed. ```bash npx @arcgis/create -n my-arcgis-app -t vite ``` -------------------------------- ### Query Feature Service Source: https://github.com/esri/jsapi-resources/blob/main/templates/geometry-operator-worker/README.md Execute a query against a feature service using specific parameters. This example uses 'esriSpatialRelContains' to find features within a buffer polygon. ```javascript const queryParams = { geometry: queryBufferPolygon, geometryType: "esriGeometryPolygon", spatialRel: "esriSpatialRelContains", returnGeometry: true, }; ``` ```javascript const featureSet = await query.executeQueryJSON(rivers, queryParams); ``` -------------------------------- ### Setup Event Listeners for Interactive Filters Source: https://github.com/esri/jsapi-resources/blob/main/layouts/interactive-filter-layout/index.html Attaches event listeners to various UI elements to handle user interactions. Use this to manage changes in lists, switches, and time toggles. ```javascript const trailListEl = document.getElementById("trail-list"); const transportListEl = document.getElementById("transport-list"); const panoramicSwitch = document.getElementById("panoramic-switch"); const winterSwitch = document.getElementById("winter-switch"); const timeToggle = document.getElementById("time-toggle"); if (trailListEl) { trailListEl.addEventListener("calciteListChange", (event) => { globalThis.handlePathsListChange?.(event); }); } if (transportListEl) { transportListEl.addEventListener("calciteListChange", (event) => { globalThis.handlePathsListChange?.(event); }); } if (panoramicSwitch) { panoramicSwitch.addEventListener("calciteSwitchChange", (event) => { globalThis.handlePathsListChange?.(event); }); } if (winterSwitch) { winterSwitch.addEventListener("calciteSwitchChange", (event) => { globalThis.handlePathsListChange?.(event); }); } if (timeToggle) { timeToggle.addEventListener("calciteTileGroupSelect", (event) => { const selected = event?.target?.selectedItems?.\ [0]; const label = (selected?.heading || "").toLowerCase(); globalThis.toggleTheme?.(label === "night"); }); } ``` -------------------------------- ### Synchronize arcgis-chart with Map View Selections Source: https://context7.com/esri/jsapi-resources/llms.txt Use the `` component to display charts from a FeatureLayer's `charts` array. Enable `syncSelectionsBetweenChartAndLayerViewPolicy` and wire `view.selectionManager` to connect chart selections with map clicks. This example demonstrates handling map clicks to update selections. ```javascript import "@arcgis/map-components/components/arcgis-map"; import "@arcgis/charts-components/components/arcgis-chart"; import "@arcgis/charts-components/components/arcgis-charts-action-bar"; const viewElement = document.querySelector("arcgis-map"); const chartElement = document.querySelector("arcgis-chart"); // viewOnReady() is a promise-based alternative to the event listener await viewElement.viewOnReady(); const view = viewElement.view; // Find and load a named layer const layer = viewElement.map?.layers.find((l) => l.title === "CollegeScorecard"); await layer.load(); // Connect the chart to the layer's first defined chart config chartElement.model = layer.charts[0]; chartElement.layer = layer; chartElement.view = view; // Enable bi-directional selection sync between chart and map view chartElement.syncSelectionsBetweenChartAndLayerViewPolicy = "enabled"; // Click on map to select features and reflect them in the chart viewElement.addEventListener("arcgisViewClick", async (event) => { const { results } = await viewElement.hitTest(event.detail, { include: [layer] }); if (results?.length > 0) { const objectIds = results.map((r) => r.graphic.getObjectId()); view.selectionManager.replace(layer, objectIds); } }); // HTML: // // ``` -------------------------------- ### Build and Preview Production App Source: https://github.com/esri/jsapi-resources/blob/main/layouts/dashboard-sample/README.md Build the production version of the app and preview it. ```bash npm run build && npm run preview ``` -------------------------------- ### Create a New ArcGIS App with AI Components Source: https://github.com/esri/jsapi-resources/blob/main/templates/ai-components-custom-agent-hil-react/README.md Use the @arcgis/create command to scaffold a new ArcGIS application with the AI components (beta) template. This command sets up the project structure and dependencies for you. ```bash npx @arcgis/create -n my-arcgis-app -t "ai-components-custom-agent-hil-react (beta)" ``` -------------------------------- ### Create ArcGIS App with Custom Agent Template Source: https://github.com/esri/jsapi-resources/blob/main/templates/ai-components-custom-agent-tools-react/README.md Use this command to create a new ArcGIS application pre-configured with the AI components custom agent tools React sample. This command sets up the project structure and dependencies. ```bash npx @arcgis/create -n my-arcgis-app -t "ai-components-custom-agent-tools-react (beta)" ``` -------------------------------- ### Create a New ArcGIS Maps SDK App with CDN Template Source: https://github.com/esri/jsapi-resources/blob/main/templates/js-maps-sdk-cdn/README.md Use this command to quickly scaffold a new application using the CDN template. This sets up the basic project structure for a CDN-based application. ```bash npx @arcgis/create -n my-arcgis-app -t cdn ``` -------------------------------- ### Configure OAuth 2.0 with Popup Callback Source: https://context7.com/esri/jsapi-resources/llms.txt Sets up OAuth 2.0 authentication for ArcGIS Online or Enterprise. Use the `popup: true` option to enable the OAuth 2.0 popup flow, which requires hosting the `oauth-callback.html` file. ```typescript import esriConfig from "@arcgis/core/config.js"; import esriId from "@arcgis/core/identity/IdentityManager.js"; import OAuthInfo from "@arcgis/core/identity/OAuthInfo.js"; export function configureOAuth({ portalUrl, appId, popup = false }) { if (portalUrl) esriConfig.portalUrl = portalUrl; const oAuthInfo = new OAuthInfo({ appId, ...(portalUrl ? { portalUrl } : {}), popup, // set true to use popup window + oauth-callback.html }); esriId.registerOAuthInfos([oAuthInfo]); } // Usage in main.ts: // configureOAuth({ appId: "YOUR_APP_ID" }); // configureOAuth({ appId: "YOUR_APP_ID", portalUrl: "https://your-portal.com", popup: true }); ``` ```html // oauth/oauth-callback.html (host in the same folder): // // ``` -------------------------------- ### Configure Maps SDK for Disconnected Environment Source: https://github.com/esri/jsapi-resources/blob/main/templates/disconnected-environment/index.html Set the `assetsPath` to point to your local SDK assets. Optionally, configure `fontsUrl` and `portalUrl` for enterprise environments. ```javascript globalThis.esriConfig = { assetsPath: "./assets", // Optional: point to your Enterprise portal and /portal/apps/fonts directory // fontsUrl: "https://.com/portal/apps/fonts/", // portalUrl: "https://.com/portal" }; ``` -------------------------------- ### Scaffold New ArcGIS React App Source: https://github.com/esri/jsapi-resources/blob/main/templates/js-maps-sdk-react/README.md Use this command to quickly create a new application based on this template. ```bash npx @arcgis/create -n my-arcgis-app -t react ``` -------------------------------- ### Scaffold a New ArcGIS Vue App Source: https://github.com/esri/jsapi-resources/blob/main/templates/js-maps-sdk-vue/README.md Run this command in your terminal to quickly scaffold a new application using this template. ```bash npx @arcgis/create -n my-arcgis-app -t vue ``` -------------------------------- ### Scaffold New Application with @arcgis/create CLI Source: https://context7.com/esri/jsapi-resources/llms.txt Use the @arcgis.js/create CLI tool to scaffold new ArcGIS applications from supported templates. Templates are available for Vite, React, Angular, Vue, Webpack, CDN, and Node.js environments. ```bash npx @arcgis/create -n my-arcgis-app -t vite ``` ```bash npx @arcgis/create -n my-arcgis-app -t react ``` ```bash npx @arcgis/create -n my-arcgis-app -t angular ``` ```bash npx @arcgis/create -n my-arcgis-app -t vue ``` ```bash npx @arcgis/create -n my-arcgis-app -t "ai-components-custom-agent-hil-react (beta)" ``` -------------------------------- ### Import SDK Modules and Initialize Map Source: https://github.com/esri/jsapi-resources/blob/main/templates/js-maps-sdk-cdn/index.html Imports necessary modules from the ArcGIS Maps SDK and sets up a basic map view. This code should be placed within a script tag or a linked JavaScript file. ```javascript const Graphic = await $arcgis.import("@arcgis/core/Graphic.js"); const Point = await $arcgis.import("@arcgis/core/geometry/Point.js"); const SimpleMarkerSymbol = await $arcgis.import("@arcgis/core/symbols/SimpleMarkerSymbol.js"); const SimpleLineSymbol = await $arcgis.import("@arcgis/core/symbols/SimpleLineSymbol.js"); ``` -------------------------------- ### Create Buffer Geometry Source: https://github.com/esri/jsapi-resources/blob/main/templates/geometry-operator-worker/README.md Instantiate a Polyline from feature geometry and then use the buffer operator to create a buffer polygon around it. Specify the unit for the buffer distance. ```javascript const riverPolyline = new Polyline({ paths: feature.geometry.paths, spatialReference: featureSet.spatialReference, }); ``` ```javascript const riverBufferPolygon = bufferOperator.execute(riverPolyline, 200, { unit: "meters", }); ``` -------------------------------- ### Create Inset Overview Map with GraphicsLayer Source: https://context7.com/esri/jsapi-resources/llms.txt Use this snippet to create a secondary 2D MapView that follows the extent of a 3D SceneView. It requires a container element with the ID 'inset-map' and synchronizes its view with the main scene. ```javascript import Map from "@arcgis/core/Map"; import MapView from "@arcgis/core/views/MapView.js"; import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer.js"; import Graphic from "@arcgis/core/Graphic.js"; import { watch } from "@arcgis/core/core/reactiveUtils.js"; export function setupInsetMap(sceneView) { const insetMap = new Map({ basemap: "gray-vector" }); const insetLayer = new GraphicsLayer(); insetMap.add(insetLayer); const insetView = new MapView({ container: document.getElementById("inset-map"), map: insetMap, center: [7.8, 46.0], zoom: 0, ui: { components: [] }, navigation: { mouseWheelZoomEnabled: false, browserTouchPanEnabled: false }, }); // Sync inset highlight with the main scene view's extent watch(() => sceneView.extent, (ext) => { if (!ext || !insetView) return; const polygon = { type: "polygon", rings: [[ [ext.xmin, ext.ymin], [ext.xmin, ext.ymax], [ext.xmax, ext.ymax], [ext.xmax, ext.ymin], [ext.xmin, ext.ymin], ]], spatialReference: ext.spatialReference, }; insetLayer.removeAll(); insetLayer.add(new Graphic({ geometry: polygon, symbol: { type: "simple-fill", color: [245, 199, 79, 0.85], outline: null }, })); insetView.goTo(ext.clone().expand(20), { animate: false }).catch(() => {}); }); } ``` -------------------------------- ### Enable .woff2 Asset Support in angular.json Source: https://github.com/esri/jsapi-resources/blob/main/templates/coding-components-angular/README.md Include this configuration in angular.json to enable support for .woff2 font files, which is necessary for font importing in Angular projects. ```json { "loader": { ".woff2": "file" } } ``` -------------------------------- ### Query Features and Apply Effects - React Finder Layout Source: https://context7.com/esri/jsapi-resources/llms.txt Demonstrates querying features from a LayerView and applying feature effects for highlighting. This pattern is useful for synchronizing map selections with a results list. ```tsx import "@arcgis/map-components/components/arcgis-map"; import "@esri/calcite-components/components/calcite-flow"; import "@esri/calcite-components/components/calcgis-flow-item"; const PAGE_SIZE = 100; async function queryItems(layerView, start = 0) { const query = layerView.layer.createQuery(); query.start = start; query.num = PAGE_SIZE; query.orderByFields = ["OBJECTID ASC"]; query.outFields = ["*"]; query.returnGeometry = true; query.where = "1=1"; const featureSet = await layerView.layer.queryFeatures(query); return featureSet.features; // array of VenueFeature graphics } // After arcgis-map fires arcgisViewReadyChange: await element.componentOnReady(); // wait for web component await element.view.when(); // wait for MapView const layer = findLayerByTitle(view.map.layers, "LA 2028 Venues"); const layerView = await view.whenLayerView(layer); const features = await queryItems(layerView); // Apply a feature effect filter (highlight selected items): layerView.featureEffect = { filter: { where: `OBJECTID IN (${ids.join(",")})` }, includedEffect: "bloom(2, 1px, 0.3)", excludedEffect: "grayscale(100%) opacity(30%)", }; // Navigate back: restore prior effect and zoom to full extent view.goTo({ target: layer.fullExtent, zoom: 10 }); ``` -------------------------------- ### Load ArcGIS SDK via CDN using Script Tag Source: https://context7.com/esri/jsapi-resources/llms.txt This HTML snippet demonstrates how to load the entire ArcGIS Maps SDK for JavaScript from the CDN using a ` ``` -------------------------------- ### Animate Scene Theme for Day/Night Lighting Source: https://context7.com/esri/jsapi-resources/llms.txt This code animates the scene's lighting date between noon and midnight for day/night transitions. It uses `requestAnimationFrame` and an easing function for a smooth visual effect. Ensure the `sceneEl` has a `view` property. ```javascript import { watch } from "@arcgis/core/core/reactiveUtils"; function easeInOutQuad(t) { return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t; } function animateLighting(view, fromDate, toDate, duration = 2000) { const start = performance.now(); return new Promise((resolve) => { function step(now) { const t = Math.min(1, (now - start) / duration); const eased = easeInOutQuad(t); view.environment.lighting.date = new Date( fromDate.getTime() + (toDate.getTime() - fromDate.getTime()) * eased ); if (t < 1) requestAnimationFrame(step); else resolve(); } requestAnimationFrame(step); }); } export async function toggleTheme(sceneEl, toDark) { document.body.classList.toggle("calcite-mode-dark", toDark); const view = sceneEl?.view; const current = new Date(view.environment.lighting.date); if (toDark) { // Animate to midnight const midnight = new Date(current); midnight.setHours(12, 0, 0, 0); await animateLighting(view, current, midnight, 2000); } else { // Animate to noon const noon = new Date(current); noon.setHours(0, 0, 0, 0); await animateLighting(view, current, noon, 2000); } } ``` -------------------------------- ### Local Asset Hosting for Disconnected Environments Source: https://context7.com/esri/jsapi-resources/llms.txt This JavaScript configuration snippet shows how to set up Vite to copy all ArcGIS Maps SDK assets locally for offline use. It involves copying assets to the `dist/assets` directory and setting the `esriConfig.assetsPath` in the application code. ```javascript // templates/disconnected-environment/vite.config (pattern) // package.json scripts copy assets before build: // "copy-assets": "cpy node_modules/@arcgis/core/assets dist/assets && ..." // Then in app code: import esriConfig from "@arcgis/core/config.js"; esriConfig.assetsPath = "./assets"; // point to locally copied assets // Install: npm install // Build: npm run build (copies assets + bundles) // Serve: npm run preview (serves entirely from dist/, no CDN calls) ``` -------------------------------- ### Scaffold a New ArcGIS Maps SDK Webpack App Source: https://github.com/esri/jsapi-resources/blob/main/templates/js-maps-sdk-webpack/README.md Run this command in your terminal to quickly set up a new application using the Webpack template for the ArcGIS Maps SDK for JavaScript. ```bash npx @arcgis/create -n my-arcgis-app -t webpack ``` -------------------------------- ### Configure Local Assets Path Source: https://github.com/esri/jsapi-resources/blob/main/templates/js-maps-sdk-node/README.md Set the assetsPath configuration when Node.js requires managing SDK assets locally. This ensures assets are correctly resolved when hosted on a web server. ```js import esriConfig from "@arcgis/core/config.js"; esriConfig.assetsPath = "https://mywebsite.com/assets"; ``` -------------------------------- ### OAuth Callback Handler Source: https://github.com/esri/jsapi-resources/blob/main/oauth/oauth-callback.html This function is executed when the OAuth callback page loads. It checks for an opener window and processes the authentication response from the URL's hash or search parameters, sending it back to the opener. ```javascript function loadHandler() { if (opener) { // opener.console.log("oauth callback href:", location.href); if (location.hash) { try { var esriId = opener.require("esri/kernel").id; } catch (e) {} if (esriId) { esriId.setOAuthResponseHash(location.hash); } else { opener.dispatchEvent(new CustomEvent("arcgis:auth:hash", { detail: location.hash })); } } else if (location.search) { opener.dispatchEvent(new CustomEvent("arcgis:auth:location:search", { detail: location.search })); } } close(); } ``` -------------------------------- ### Scaffold New Angular App with ArcGIS Maps SDK Source: https://github.com/esri/jsapi-resources/blob/main/templates/js-maps-sdk-angular/README.md Use this command to quickly create a new Angular application pre-configured with the ArcGIS Maps SDK for JavaScript. ```bash npx @arcgis/create -n my-arcgis-app -t angular ``` -------------------------------- ### Define Unique Value Renderer for Hiking Paths Source: https://context7.com/esri/jsapi-resources/llms.txt Creates a `UniqueValueRenderer` to style hiking paths based on their 'difficulty' field. Each difficulty level ('easy', 'medium', 'difficult') is assigned a unique `LineSymbol3D` with different colors and patterns. The renderer is then applied to the 'HikingPaths' layer. ```javascript import UniqueValueRenderer from "@arcgis/core/renderers/UniqueValueRenderer.js"; // UniqueValueRenderer for hiking paths by difficulty export const hikingPathRenderer = new UniqueValueRenderer({ field: "difficulty", uniqueValueInfos: [ { value: "easy", symbol: makeLineSymbol3D([46, 125, 50], "solid", 3) }, { value: "medium", symbol: makeLineSymbol3D([33, 150, 243], "dash", 3) }, { value: "difficult", symbol: makeLineSymbol3D([15, 15, 15], "dot", 3) }, ], }); // Apply to a layer found in the scene const hikingPathLayer = sceneEl.map.allLayers.find((l) => l.title === "HikingPaths"); hikingPathLayer.renderer = hikingPathRenderer; ``` -------------------------------- ### Initialize Comlink Worker Source: https://github.com/esri/jsapi-resources/blob/main/templates/geometry-operator-worker/README.md Create a new worker thread for geometry operations using Comlink. Ensure the worker module is correctly imported. ```javascript const geometryOperatorsWorker = new ComlinkWorker(new URL("./geometry-operators-worker.mjs", import.meta.url), { name: "geometryOperatorWorker", type: "module", }); ``` -------------------------------- ### TypeScript Configuration for Vite Source: https://github.com/esri/jsapi-resources/blob/main/templates/js-maps-sdk-vite/README.md This template is pre-configured for TypeScript. To switch to JavaScript, remove the tsconfig.json file, update file extensions, and remove the typescript dependency from package.json. ```json { "compilerOptions": { "target": "ES2020", "module": "ESNext", "lib": [ "ES2020", "DOM" ], "jsx": "react-jsx", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "moduleResolution": "node", "resolveJsonModule": true, "allowSyntheticDefaultImports": true, "isolatedModules": true, "noEmit": true }, "include": [ "src" ], "exclude": [ "node_modules" ] } ``` -------------------------------- ### Configure .ttf Loader in angular.json Source: https://github.com/esri/jsapi-resources/blob/main/templates/coding-components-angular/README.md Add this configuration to angular.json to resolve build errors related to .ttf files, often encountered with Monaco Editor. ```json { "loader": { ".ttf": "file" } } ``` -------------------------------- ### Configure Interactive 3D Scene with arcgis-scene Source: https://context7.com/esri/jsapi-resources/llms.txt Use the `` component to render a 3D scene. Listen for the `arcgisViewReadyChange` event to configure camera position, altitude, heading, tilt, and view constraints. Watch for camera and scale changes to log view properties. ```javascript import { watch } from "@arcgis/core/core/reactiveUtils"; import "@arcgis/map-components/components/arcgis-scene"; import "@arcgis/map-components/components/arcgis-daylight"; const sceneEl = document.querySelector("arcgis-scene"); sceneEl.addEventListener("arcgisViewReadyChange", async () => { const map = sceneEl.map; const view = sceneEl.view; // Wait for view to be fully ready await view.when(); // Set camera position over the Swiss Alps sceneEl.camera = { position: { longitude: 7.8304, latitude: 46.3516, z: 8000 }, altitude: 9196.4666, heading: 188.7133, tilt: 79.6, }; // Constrain altitude and tilt ranges view.constraints = { altitude: { min: 4000, max: 15000 }, tilt: { min: 45, max: 80 }, geometry: { type: "extent", xmin: 7, ymin: 45.0, xmax: 9.0, ymax: 47.0, spatialReference: { wkid: 4326 }, }, }; // Watch camera and scale changes reactively watch( () => [view.camera, view.scale], () => { const { position } = view.camera; console.log("Camera:", position.longitude, position.latitude, position.z); }, ); }); ``` -------------------------------- ### Offload Geometry Operations to Web Worker with Comlink Source: https://context7.com/esri/jsapi-resources/llms.txt This snippet demonstrates how to use Comlink to move heavy spatial processing, such as buffering and generalizing geometries, to a background thread. This prevents the main UI thread from freezing during intensive computations. Ensure Comlink is set up for worker communication. ```javascript // templates/geometry-operator-worker/src/geometry-operator-worker.mjs import * as bufferOperator from "@arcgis/core/geometry/operators/bufferOperator.js"; import * as generalizeOperator from "@arcgis/core/geometry/operators/generalizeOperator.js"; import * as lengthOperator from "@arcgis/core/geometry/operators/lengthOperator.js"; import Polyline from "@arcgis/core/geometry/Polyline.js"; import Polygon from "@arcgis/core/geometry/Polygon.js"; import * as query from "@arcgis/core/rest/query.js"; export async function getRiverBuffers(queryBufferJSON) { const rivers = "https://livefeeds3.arcgis.com/arcgis/rest/services/NationalWaterModel/Medium_Range_Anomaly/MapServer/0/query"; const queryBufferPolygon = new Polygon({ rings: queryBufferJSON.rings, spatialReference: queryBufferJSON.spatialReference, }); const featureSet = await query.executeQueryJSON(rivers, { where: "1=1", geometry: queryBufferPolygon, geometryType: "esriGeometryPolygon", spatialRel: "esriSpatialRelContains", returnGeometry: true, }); return { riversLength: featureSet.features.reduce((total, f) => { const polyline = new Polyline({ paths: f.geometry.paths, spatialReference: featureSet.spatialReference }); return total + lengthOperator.execute(polyline); }, 0), bufferedFeatureSet: featureSet.features.map((f) => { const riverPolyline = new Polyline({ paths: f.geometry.paths, spatialReference: featureSet.spatialReference }); const buffer = bufferOperator.execute(riverPolyline, 200, { unit: "meters" }); return { rivers: generalizeOperator.execute(riverPolyline, 10, { unit: "meters" }).toJSON(), riverBuffers: generalizeOperator.execute(buffer, 10, { unit: "meters" }).toJSON(), }; }), }; } // Main thread usage (templates/geometry-operator-worker/src/main.js): // const worker = new ComlinkWorker(new URL("./geometry-operator-worker.mjs", import.meta.url), { type: "module" }); // const queryBuffer = bufferOperator.execute(event.detail.mapPoint, 10000, { unit: "meters" }); // const result = await worker.getRiverBuffers(queryBuffer.toJSON()); // const rivers = result.bufferedFeatureSet.map((f) => Graphic.fromJSON(f.rivers)); ``` -------------------------------- ### Create Custom 3D Line Symbols with Patterns Source: https://context7.com/esri/jsapi-resources/llms.txt A helper function to generate `LineSymbol3D` objects with customizable color, pattern, and width. It supports predefined patterns like 'dash' and 'dot', or a 'solid' pattern if none is specified. Requires imports from '@arcgis/core'. ```javascript import Color from "@arcgis/core/Color.js"; import LineSymbol3D from "@arcgis/core/symbols/LineSymbol3D.js"; import LineSymbol3DLayer from "@arcgis/core/symbols/LineSymbol3DLayer.js"; import LineStylePattern3D from "@arcgis/core/symbols/patterns/LineStylePattern3D.js"; function makeLineSymbol3D(color, pattern = "solid", width = 4) { return new LineSymbol3D({ symbolLayers: [ new LineSymbol3DLayer({ material: { color: new Color(color) }, size: `${width}px`, cap: "round", join: "round", pattern: pattern === "solid" ? undefined : new LineStylePattern3D({ style: pattern }), }), ], }); } ``` -------------------------------- ### Generalize Geometry Source: https://github.com/esri/jsapi-resources/blob/main/templates/geometry-operator-worker/README.md Simplify polyline and buffer polygon geometries using the generalize operator. This reduces the number of vertices, improving serialization performance while preserving the overall shape. ```javascript // Generalize the polylines and buffer polygons to simplify the shape and reduce the number of vertices. const generalizedPolyline = generalizeOperator.execute(riverPolyline, 10, { unit: "meters", }); ``` ```javascript const generalizedRiverBufferPolygon = generalizeOperator.execute(riverBufferPolygon, 10, { unit: "meters", }); ``` -------------------------------- ### Server-Side Geometry Projection in Node.js Source: https://context7.com/esri/jsapi-resources/llms.txt This snippet shows how to perform geometry projection using the `@arcgis/core` library within a Node.js environment. It requires loading the projection operator, which downloads necessary WebAssembly files from a CDN by default. This is useful for headless applications needing spatial transformations. ```javascript // templates/js-maps-sdk-node/projection.js import * as projectOperator from "@arcgis/core/geometry/operators/projectOperator.js"; import Point from "@arcgis/core/geometry/Point.js"; // Load the operator (downloads .wasm from CDN by default) await projectOperator.load(); const projected = projectOperator.execute( new Point({ x: -117, y: 34 }), { wkid: 3857 } // project from WGS84 to Web Mercator ); console.log(projected.toJSON()); // → { x: -13025664...., y: 4028802..., spatialReference: { wkid: 102100 } } ``` -------------------------------- ### Apply Winter Weather Effects to SceneView Source: https://context7.com/esri/jsapi-resources/llms.txt Sets the SceneView environment to a snowy weather type with specified cloud cover and precipitation. 'savedWeather' should be defined to restore previous weather settings. ```javascript export function applyWinterService(view) { view.environment.weather = { type: "snowy", cloudCover: 0.8, precipitation: 0.3, snowCover: "enabled", }; } ``` -------------------------------- ### Compute Power Plant Metrics - Utility Function Source: https://context7.com/esri/jsapi-resources/llms.txt Calculates metrics for power plants, including total count and renewable percentage. This function is used within the React context provider. ```ts export function computeMetrics(plants) { const total = plants.length; const renewableFuels = ["hydro","solar","wind","biomass","geothermal","wave","tidal","cogeneration","storage"]; const renewable = plants.filter((p) => renewableFuels.includes(p.fuel.toLowerCase())); return { totalPlants: total, renewablePercent: total ? Math.round((renewable.length / total) * 100) : 0, nonRenewablePercent: total ? Math.round(((total - renewable.length) / total) * 100) : 0, topFuelType: /* most common fuel */ "gas", }; } ``` -------------------------------- ### Handle Interactive Filter Changes for 3D Layers Source: https://context7.com/esri/jsapi-resources/llms.txt This function updates layer filters based on selected items from lists. It applies a 'where' clause to the 'hiking' layer and conditionally applies a 'bloom' effect for panoramic trails. Ensure 'trailListEl' and 'transportListEl' are defined and populated. ```javascript export function handlePathsListChange(sceneEl) { const selectedItems = [...trailListEl?.selectedItems, ...transportListEl?.selectedItems]; const selections = selectedItems.reduce( (acc, item) => { const [layer, filter] = (item.value || "").split(":"); if (layer === "hiking") acc.hiking.push(filter); if (layer === "cablecar") acc.cable.push(filter); if (layer === "railway") acc.railway = true; return acc; }, { hiking: [], cable: [], railway: false }, ); // Apply where clause filter to layerView const hikingWhere = selections.hiking.length ? `difficulty IN (${selections.hiking.map((v) => `'${v}'`).join(", ")})` : null; hikingView.filter = hikingWhere ? { where: hikingWhere } : null; // Bloom effect for panoramic trails hikingView.featureEffect = panoramicSelected ? { filter: { where: hikingWhere }, includedEffect: "bloom(3.2, 2.4px, 0.65)" } : null; } ``` -------------------------------- ### Include ArcGIS Maps SDK for JavaScript via CDN Source: https://github.com/esri/jsapi-resources/blob/main/templates/js-maps-sdk-cdn/README.md Add this script tag to your HTML file to load all necessary packages for the ArcGIS Maps SDK for JavaScript from the CDN. This is essential for using the SDK in a web application. ```html ``` -------------------------------- ### Query Power Plants Data - React Context Source: https://context7.com/esri/jsapi-resources/llms.txt Queries a FeatureLayer for power plant data and processes it for use in a React application. This function should be called after the arcgis-map component raises the arcgisViewReadyChange event. ```tsx import { useEffect, useMemo, useState } from "react"; import { computeMetrics } from "../utils/Metrics"; export function AppProvider({ children }: { children: React.ReactNode }) { const [powerPlants, setPowerPlants] = useState([]); const [plantTypeFilter, setPlantTypeFilter] = useState("all"); const filteredPlants = useMemo( () => plantTypeFilter === "all" ? powerPlants : powerPlants.filter((p) => p.fuel === plantTypeFilter), [powerPlants, plantTypeFilter], ); const metrics = useMemo(() => computeMetrics(filteredPlants), [filteredPlants]); // Query a FeatureLayer after the arcgis-map raises arcgisViewReadyChange const queryPowerPlants = async (featureLayer) => { await featureLayer.load(); const result = await featureLayer.queryFeatures({ where: "1=1", outFields: ["name", "fuel1", "capacity_mw", "estimated_generation_gwh"], returnGeometry: false, }); return result.features.map((f) => ({ name: f.attributes.name || "Unknown", fuel: f.attributes.fuel1?.toLowerCase().replace(/ /gu, "") || "other", capacity: Number(f.attributes.capacity_mw || 0), generation: Number(f.attributes.estimated_generation_gwh || 0), })); }; // Dashboard renders using calcite-shell and arcgis-map: // // // // } ``` -------------------------------- ### Integrate ArcGIS Arcade Editor in React Source: https://context7.com/esri/jsapi-resources/llms.txt Embeds the `@arcgis/coding-components` Arcade editor into a React application. It requires loading a WebMap and FeatureLayer to provide context for Arcade expression development. ```jsx import "@arcgis/coding-components/components/arcgis-arcade-editor"; import "@esri/calcite-components/components/calcite-scrim"; import WebMap from "@arcgis/core/WebMap"; async function loadData() { const webMap = new WebMap({ portalItem: { id: "93d14bfd59a84af0be99a883feba052b" } }); await webMap.loadAll(); const featureLayer = webMap.findLayerById("17c807fd286-layer-47"); const featureSet = await featureLayer.queryFeatures({ where: "1=1", outFields: ["*"], returnGeometry: true, }); return { webMap, featureLayer, featureSet }; } export default function ArcadeEditor() { const data = useArcadeEditorData(); // loads webMap, featureLayer, featureSet return ( console.log("script:", e.detail)} onarcgisDiagnosticsChange={(e) => console.log("diagnostics:", e.detail)} profile={{ id: "popup", definitions: { $feature: data.featureLayer, // metadata only (not a feature instance) $layer: data.featureLayer, $map: data.webMap, $datastore: data.featureLayer, }, }} testData={{ profileVariableInstances: { $feature: data.featureSet.features[0], // actual feature instance for test execution $layer: data.featureLayer, $map: data.webMap, $datastore: data.featureLayer.url, }, }} /> ); } ``` -------------------------------- ### Add Custom Graphic to Map Source: https://github.com/esri/jsapi-resources/blob/main/templates/js-maps-sdk-cdn/index.html Defines a point graphic with a custom symbol and adds it to the map view. This is useful for visualizing specific locations or data points not present in the initial web map. ```javascript const viewElement = document.querySelector("arcgis-map"); const calciteNavLogo = document.querySelector("calcite-navigation-logo"); viewElement.addEventListener("arcgisViewReadyChange", () => { const { title, description } = viewElement.map.portalItem; if (calciteNavLogo) { calciteNavLogo.heading = title === "" ? "A web map" : title; calciteNavLogo.description = description === "" ? "ArcGIS Maps SDK for JavaScript template" : description; } const point = new Point({ longitude: -98.38, latitude: 38.34, }); const outline = new SimpleLineSymbol({ color: "white", width: 2, }); const symbol = new SimpleMarkerSymbol({ style: "triangle", size: 20, color: "red", outline, }); const pointGraphic = new Graphic({ geometry: point, symbol, }); viewElement.graphics.add(pointGraphic); }); ``` -------------------------------- ### Embed Map with arcgis-map Web Component Source: https://context7.com/esri/jsapi-resources/llms.txt The web component renders a 2D MapView or 3D SceneView declaratively. It fires 'arcgisViewReadyChange' when the view is ready and allows programmatic access to add graphics. ```tsx import "@arcgis/map-components/components/arcgis-map"; import "@arcgis/map-components/components/arcgis-zoom"; import "@arcgis/map-components/components/arcgis-legend"; import "@arcgis/map-components/components/arcgis-expand"; import "@arcgis/map-components/components/arcgis-search"; import Graphic from "@arcgis/core/Graphic.js"; import Point from "@arcgis/core/geometry/Point.js"; import SimpleMarkerSymbol from "@arcgis/core/symbols/SimpleMarkerSymbol.js"; import type WebMap from "@arcgis/core/WebMap"; const viewElement = document.querySelector("arcgis-map"); viewElement?.addEventListener("arcgisViewReadyChange", () => { const map = viewElement.map as WebMap; // Access portal metadata const title = map.portalItem?.title ?? "A web map"; // Add a custom graphic programmatically const point = new Point({ longitude: -98.38, latitude: 38.34 }); const symbol = new SimpleMarkerSymbol({ style: "triangle", size: 20, color: "red", outline: { color: "white", width: 2 }, }); const pointGraphic = new Graphic({ geometry: point, symbol }); viewElement.graphics.add(pointGraphic); }); // Corresponding HTML // // // // // // ``` -------------------------------- ### Define and Register Maintenance Service Agent Source: https://context7.com/esri/jsapi-resources/llms.txt This TypeScript code defines a custom LangGraph agent for reporting street maintenance issues. It includes state definitions, LLM-based data extraction, a HIL interrupt for user confirmation, and persistence to a FeatureLayer. The agent is registered for use with the arcgis-assistant web component. ```typescript import { StateGraph, START, END, Annotation, messagesStateReducer, NodeInterrupt, } from "@langchain/langgraph/web"; import { invokeStructuredPrompt, sendTraceMessage, } from "@arcgis/ai-components/utils/index.js"; import type { AgentRegistration, UiInterrupt, } from "@arcgis/ai-components/utils/index.js"; import z from "zod"; import FeatureLayer from "@arcgis/core/layers/FeatureLayer.js"; import Graphic from "@arcgis/core/Graphic.js"; // 1. Define state const ServiceMaintenanceState = Annotation.Root({ messages: Annotation({ reducer: messagesStateReducer, default: () => [], }), outputMessage: Annotation({ reducer: (cur = "", upd) => (upd?.trim() ? `${cur}\n\n${upd}` : cur), default: () => "", }), ticket: Annotation({ reducer: (_, upd) => upd ?? null, default: () => null, }), }); // 2. Node: extract ticket fields using a structured LLM prompt const extractMaintenanceLLM = async (state, config) => { const schema = z.object({ category: z.enum([ "Pothole", "Cracks", "Faded Paint", "Debris", "Erosion", "Blockage", "Other", ]), notes: z.string(), severity: z.enum(["Low", "Moderate", "High", "Critical"]), address: z.string(), }); const response = await invokeStructuredPrompt({ promptText: "Extract road maintenance issue details from the user message...", modelTier: "default", messages: state.messages, schema, }); return { ticket: { ...response, CreationDate: new Date() } }; }; // 3. Node: HIL interrupt — pause graph and ask user to confirm const approvalMaintenance = (state, config) => { const { hitlResponse } = config.configurable; if (!hitlResponse || hitlResponse.id !== "approveMaintenanceTicket") { // Interrupt with a single-selection prompt throw new NodeInterrupt({ agentId: "serviceMaintenance", id: "approveMaintenanceTicket", kind: "singleSelection", message: `I've prepared a ${state.ticket.category} report at ${state.ticket.address}. Proceed?`, metadata: ["Yes", "No", "Maybe later"], } as UiInterrupt); } return hitlResponse.payload === "Yes" ? state : { outputMessage: "Cancelled.", ticket: null }; }; // 4. Node: persist approved ticket to FeatureLayer const persistMaintenance = async (state, config) => { const layer = config.configurable.context.mapView.map.layers.find( (l) => l.title === "Maintenance issues" ) as FeatureLayer; await layer.applyEdits({ addFeatures: [ new Graphic({ geometry: config.configurable.context.mapView.center, attributes: state.ticket, }), ], }); return { outputMessage: `Logged: ${state.ticket.category} at ${state.ticket.address}` }; }; // 5. Register agent export const ServiceMaintenanceAgent: AgentRegistration = { id: "serviceMaintenance", name: "Maintenance Service Agent", description: "Reports street maintenance issues (potholes, faded paint, debris, etc.)", createGraph: () => new StateGraph(ServiceMaintenanceState) .addNode("extractMaintenanceLLM", extractMaintenanceLLM) .addNode("approvalMaintenance", approvalMaintenance) .addNode("persistMaintenance", persistMaintenance) .addEdge(START, "extractMaintenanceLLM") .addEdge("extractMaintenanceLLM", "approvalMaintenance") .addEdge("approvalMaintenance", "persistMaintenance") .addEdge("persistMaintenance", END), workspace: ServiceMaintenanceState, }; // App.tsx usage: // // // // // ``` -------------------------------- ### Call Worker Method Source: https://github.com/esri/jsapi-resources/blob/main/templates/geometry-operator-worker/README.md Invoke a method on the Comlink worker to perform geometry operations. Pass necessary data, such as a JSON representation of a buffer polygon. ```javascript const result = await geometryOperatorWorker.getRiverBuffers(queryBuffer.toJSON()); ``` -------------------------------- ### Clear Winter Weather Effects from SceneView Source: https://context7.com/esri/jsapi-resources/llms.txt Resets the SceneView's weather to its previously saved state or null if no state was saved. This function is used to remove custom weather effects. ```javascript export function clearWinterService(view) { view.environment.weather = savedWeather || null; } ```