Learn how to execute a spatial query to access features from a feature layer.
A feature layer can contain a large number of features stored in ArcGIS. To access a subset of the features, you can execute either a SQL or spatial query, or both at the same time. You can return feature attributes, geometry, or both attributes and geometry for each record. SQL and spatial queries are useful when you want to access just a subset of your hosted data.
In this tutorial, you will use the Sketch
component to draw a feature and then perform a spatial query against a feature layer. The query layer is the LA County Parcels feature layer containing ±2.4 million features. The spatial query uses the sketched feature to return all of the parcels that intersect.
Prerequisites
Steps
Create a new pen
- To get started, either complete the Display a map tutorial or .
Get an access token
You need an access token with the correct privileges to access the location services used in this tutorial.
- Go to the Create an API key tutorial and create an API key with the following privilege(s):
- Privileges
- Location services > Basemaps
- Item access
- Note: If you are using your own custom data layer for this tutorial, you need to grant the API key credentials access to the layer item. Learn more in Item access privileges.
- Privileges
- In CodePen, set
esri
to your access token.Config.api Key Use dark colors for code blocks var esriConfig = { apiKey: "YOUR_ACCESS_TOKEN" };
To learn about other ways to get an access token, go to Types of authentication.
Add a Sketch component
Use the Sketch
component to create a graphic. The graphic will be added to the map in a graphics layer. The event handler will listen for a change from the Sketch component and update the query accordingly.
-
Add an
arcgis-sketch
component after thearcgis-zoom
component within the<arcgis-map
. Set the> position
attribute totop-right
and thecreation-mode
attribute toupdate
.Use dark colors for code blocks <arcgis-map basemap="topo" center="-118.805, 34.027" zoom="13"> <arcgis-zoom position="top-left"></arcgis-zoom> <arcgis-sketch creation-mode="update" position="top-right"></arcgis-sketch> </arcgis-map>
-
You should see the Sketch component at the top right of the map. Click on one of the options in the component to draw on the map.
Add modules and event listeners
-
Add a
<script
tag in the> <body
following the> <arcgis-map
component with a> require
statement. In therequire
statement, add theFeature
module.Layer The ArcGIS Maps SDK for JavaScript is available as AMD modules and ES modules, but this tutorial is based on AMD. The AMD
require
function uses references to determine which modules will be loaded – for example, you can specify"esri/layers/
for loading the FeatureLayer module. After the modules are loaded, they are passed as parameters (e.g.Feature Layer" Feature
) to the callback function where they can be used in your application. It is important to keep the module references and callback parameters in the same order. To learn more about the API's different modules visit the Overview Guide page.Layer Within the require statement, use the document.querySelector() method to access the map and sketch components.
Use dark colors for code blocks <script> require(["esri/layers/FeatureLayer"], (FeatureLayer) => { const arcgisMap = document.querySelector("arcgis-map"); const arcgisSketch = document.querySelector("arcgis-sketch"); }); </script>
-
Create an event listener to listen for the map component's
arcgis
event.View Ready Change Use dark colors for code blocks require(["esri/layers/FeatureLayer"], (FeatureLayer) => { const arcgisMap = document.querySelector("arcgis-map"); const arcgisSketch = document.querySelector("arcgis-sketch"); arcgisMap.addEventListener("arcgisViewReadyChange", () => { }); });
-
In the
arcgis
event listener, create an event listener that will update each time a graphic is drawn. You'll use this to run a new query in the next step.View Ready Change Use dark colors for code blocks arcgisMap.addEventListener("arcgisViewReadyChange", () => { arcgisSketch.addEventListener("arcgisUpdate", (event) => { }); });
Create a feature layer to query
Use the Feature
class to perform a query against the LA County Parcels feature layer. Since you are performing a server-side query, the feature layer does not need to be added to the map.
-
Create a
parcel
and set theLayer url
property to access the feature layer in the feature service.Feature layers are referenced by an index number at the end of the url. To determine the index number, visit the LA County Parcels feature service. In this case the index is
0
.Use dark colors for code blocks // Reference query layer const parcelLayer = new FeatureLayer({ url: "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0" });
Execute the query
Define a parcel
and use the Feature
query
method to execute a query.
-
Create a
query
function withFeaturelayer geometry
as a parameter and defineparcel
. Set theQuery spatial
toRelationship intersects
and use thegeometry
from the sketch component. Limit the attributes returned by setting theout
property to a list of fields. Lastly, setFields return
toGeometry true
so the feature geometries can be displayed.Use dark colors for code blocks function queryFeaturelayer(geometry) { console.log("Querying parcels..."); const parcelQuery = { spatialRelationship: "intersects", // Relationship operation to apply geometry: geometry, // The sketch feature geometry outFields: ["APN", "UseType", "TaxRateCity", "Roll_LandValue"], // Attributes to return returnGeometry: true }; }
-
Call the
query
method on theFeatures parcel
using the parameters defined in theLayer parcel
element. To view the number of features returned, write the result length to the console. This will be updated in the next step.Query Use dark colors for code blocks function queryFeaturelayer(geometry) { console.log("Querying parcels..."); const parcelQuery = { spatialRelationship: "intersects", // Relationship operation to apply geometry: geometry, // The sketch feature geometry outFields: ["APN", "UseType", "TaxRateCity", "Roll_LandValue"], // Attributes to return returnGeometry: true }; parcelLayer .queryFeatures(parcelQuery) .then((results) => { console.log("Feature count: " + results.features.length); }) .catch((error) => { console.log(error); }); }
-
Update the sketch event handler to call the
query
function every time a graphic is sketched on the map. It will also listen for any reshape or move changes made to the graphic.Feature Layer Use dark colors for code blocks arcgisSketch.addEventListener("arcgisUpdate", (event) => { // Create if (event.detail.state === "start") { queryFeaturelayer(event.detail.graphics[0].geometry); } if (event.detail.state === "complete") { // Clear the graphic when a user clicks off of it or sketches new one arcgisSketch.layer.remove(event.detail.graphics[0]); } // Change if ( event.detail.toolEventInfo && (event.detail.toolEventInfo.type === "scale-stop" || event.detail.toolEventInfo.type === "reshape-stop" || event.detail.toolEventInfo.type === "move-stop") ) { queryFeaturelayer(event.detail.graphics[0].geometry); } });
-
Use the component to draw a graphic. At the bottom left, click Console to view the number of features returned from the query.
Display features
To display the parcel features returned from the query, add them to the map as polygon graphics. Before the graphics are added, define a symbol and a pop-up so that the attributes can be displayed when a feature is clicked.
-
Create a
display
function. Define aResults symbol
andpopup
variable to style and display a pop-up for polygon graphics. The attributes referenced match theTemplate out
specified in the query earlier.Fields Use dark colors for code blocks // Show features (graphics) function displayResults(results) { // Create a blue polygon const symbol = { type: "simple-fill", color: [20, 130, 200, 0.5], outline: { color: "white", width: 0.5 } }; const popupTemplate = { title: "Parcel {APN}", content: "Type: {UseType} <br> Land value: {Roll_LandValue} <br> Tax Rate City: {TaxRateCity}" }; }
-
Assign the
symbol
andpopup
elements to each feature returned from the query.Template Use dark colors for code blocks const popupTemplate = { title: "Parcel {APN}", content: "Type: {UseType} <br> Land value: {Roll_LandValue} <br> Tax Rate City: {TaxRateCity}" }; // Set symbol and popup results.features.forEach((feature) => { feature.symbol = symbol; feature.popupTemplate = popupTemplate; });
-
Clear the existing graphics and pop-up, and then add the new features to the map as graphics.
Use dark colors for code blocks // Set symbol and popup results.features.forEach((feature) => { feature.symbol = symbol; feature.popupTemplate = popupTemplate; }); // Clear display arcgisMap.closePopup(); arcgisMap.graphics.removeAll(); // Add features to graphics layer arcgisMap.graphics.addMany(results.features);
-
Update the
query
function to call theFeaturelayer display
function. Remove theResults console.log
.Use dark colors for code blocks parcelLayer .queryFeatures(parcelQuery) .then((results) => { console.log("Feature count: " + results.features.length); displayResults(results); }) .catch((error) => { console.log(error); });
Run the app
In CodePen, run your code to display the map.
When you use the component to sketch a feature on the map, the spatial query runs against the feature layer and returns all parcels that intersect the sketched feature.
What's next?
Learn how to use additional API features and ArcGIS services in these tutorials: