Learn how to execute a SQL query to access polygon 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 only a subset of your hosted data.
In this tutorial, you will perform server-side SQL queries to return a subset of features in the LA County Parcel feature layer. The feature layer contains over 2.4 million features. The resulting features are displayed as graphics on the map.
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.
Create a SQL selector
ArcGIS feature layers support a standard SQL query where clause. Use a Calcite Select component to provide a list of SQL queries for the LA County Parcels feature layer.
-
Add an
arcgis-placement
component after thearcgis-zoom
component within the<arcgis-map
to place the selector in the> top-right
corner of the map.Use dark colors for code blocks <arcgis-map basemap="arcgis/topographic" center="-118.805, 34.027" zoom="13"> <arcgis-zoom position="top-left"></arcgis-zoom> <arcgis-placement position="top-right"> </arcgis-placement> </arcgis-map>
-
Add a Calcite Select component within the
arcgis-placement
component. This component has child option components, each with a different SQL query.Use dark colors for code blocks <arcgis-placement position="top-right"> <calcite-select id="sqlSelect"> <calcite-option id="defaultOption" value="1=0" label="Choose a SQL where clause..."></calcite-option> <calcite-option value="UseType = 'Residential'" label="UseType = 'Residential'"></calcite-option> <calcite-option value="UseType = 'Government'" label="UseType = 'Government'"></calcite-option> <calcite-option value="UseType = 'Irrigated Farm'" label="UseType = 'Irrigated Farm'"></calcite-option> <calcite-option value="TaxRateArea = 10853" label="TaxRateArea = 10853"></calcite-option> <calcite-option value="TaxRateArea = 10860" label="TaxRateArea = 10860"></calcite-option> <calcite-option value="TaxRateArea = 08637" label="TaxRateArea = 08637"></calcite-option> <calcite-option value="Roll_LandValue > 1000000" label="Roll_LandValue > 1000000"></calcite-option> <calcite-option value="Roll_LandValue < 1000000" label="Roll_LandValue < 1000000"></calcite-option> </calcite-select> </arcgis-placement>
-
Verify that the
select
component is created.
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, select, and the default option components. Create a
where
variable to store the first option value.Clause Use dark colors for code blocks <script> require(["esri/layers/FeatureLayer"], (FeatureLayer) => { const arcgisMap = document.querySelector("arcgis-map"); const selectFilter = document.querySelector("#sqlSelect"); const defaultOption = document.querySelector("#defaultOption"); let whereClause = defaultOption.value; }); </script>
-
Create an event listener to listen for the map component's
arcgis
event.View Ready Change Use dark colors for code blocks <script> require(["esri/layers/FeatureLayer"], (FeatureLayer) => { const arcgisMap = document.querySelector("arcgis-map"); const selectFilter = document.querySelector("#sqlSelect"); const defaultOption = document.querySelector("#defaultOption"); let whereClause = defaultOption.value; arcgisMap.addEventListener("arcgisViewReadyChange", () => { }); }); </script>
-
Create an event listener to listen for the
select
component changes and update thewhere
variable to the selected value.Clause Use dark colors for code blocks arcgisMap.addEventListener("arcgisViewReadyChange", () => { // Event listener selectFilter.addEventListener("calciteSelectChange", (event) => { whereClause = event.target.value; }); });
Create a feature layer to query
Use the Feature
class to access the LA County Parcel 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.Use dark colors for code blocks arcgisMap.addEventListener("arcgisViewReadyChange", () => { // Event listener selectFilter.addEventListener("calciteSelectChange", (event) => { whereClause = event.target.value; }); // Get query layer and set up query const parcelLayer = new FeatureLayer({ url: "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0" }); });
Execute a query
Use the query
method to perform a SQL query against the feature layer. The Query
will be autocast when the method is called.
-
Create a
query
function withFeature Layer extent
parameter. Define aparcel
element and set theQuery where
property to thewhere
. Set theClause spatial
to only return features that intersect theProperty geometry
, which is restricted to the visibleextent
of the map. Theout
property will return only a subset of the attributes. Lastly, setFields return
toGeometry true
so that the features can be displayed.Use dark colors for code blocks // Get query layer and set up query const parcelLayer = new FeatureLayer({ url: "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0" }); function queryFeatureLayer(extent) { const parcelQuery = { where: whereClause, // Set by select element spatialRelationship: "intersects", // Relationship operation to apply geometry: extent, // Restricted to visible extent of the map outFields: ["APN", "UseType", "TaxRateCity", "Roll_LandValue"], // Attributes to return returnGeometry: true }; }
-
Call the
query
method on theFeatures parcel
usingLayer parcel
. 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(extent) { const parcelQuery = { where: whereClause, // Set by select element spatialRelationship: "intersects", // Relationship operation to apply geometry: extent, // Restricted to visible extent of the map 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.error); }); }
-
Update the event handler to call the
query
function when the selector changes.Feature Layer Use dark colors for code blocks // Event listener selectFilter.addEventListener("calciteSelectChange", (event) => { whereClause = event.target.value; queryFeatureLayer(arcgisMap.extent); });
-
At the top-right, click Run. Choose a SQL query from the selector. At the bottom left, click Console to view the number of features returned from each query.
Display features
To display the features returned from the SQL query, add them to the view as polygon graphics. Define a pop-up also so the attributes can be displayed when features are clicked.
-
Create a
display
function withResults results
as a parameter. Define asymbol
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 }) .catch((error) => { console.log(error.error); }); } 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}" }; // Assign styles and popup to features results.features.map((feature) => { feature.symbol = symbol; feature.popupTemplate = popupTemplate; return feature; });
-
Clear the existing graphics and pop-up, and then add the new features returned to the
view
.Use dark colors for code blocks // Assign styles and popup to features results.features.map((feature) => { feature.symbol = symbol; feature.popupTemplate = popupTemplate; return feature; }); // Clear display arcgisMap.closePopup(); arcgisMap.graphics.removeAll(); // Add features to graphics layer arcgisMap.graphics.addMany(results.features);
-
Update the
query
function to call theFeature Layer 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.error); });
Run the app
In CodePen, run your code to display the map.
When the map displays, you should be able to choose a SQL query from the selector. The resulting features will be added to the map as polygon graphics. The SQL query is applied to the visible extent of the map.
What's next?
Learn how to use additional API features and ArcGIS services in these tutorials: