Learn how to execute a SQL query to return features from a feature layer based on spatial and attribute criteria.
A feature layer can contain a large number of features stored in ArcGIS. You can query a layer to access a subset of its features using any combination of spatial and attribute criteria. You can control whether or not each feature's geometry is returned, as well as which attributes are included in the results. Queries allow you to return a well-defined subset of your hosted data for analysis or display in your app.
In this tutorial, you'll write code to perform SQL queries that return a subset of features in the LA County Parcel feature layer (containing over 2.4 million features). Features that meet the query criteria are selected in the map.
Prerequisites
Before starting this tutorial:
-
You need an ArcGIS Location Platform or ArcGIS Online account.
-
Ensure your development environment meets the system requirements.
Optionally, you may want to install the ArcGIS Maps SDK for .NET to get access to project templates in Visual Studio (Windows only) and offline copies of the NuGet packages.
Steps
Open a Visual Studio solution
-
To start the tutorial, complete the Display a map tutorial or download and unzip the solution.
-
Open the
.sln
file in Visual Studio. -
If you downloaded the solution, get an access token and set the API key.
An API Key gives your app access to secure resources used in this tutorial.
-
Go to the Create an API key tutorial to obtain a new API key access token. Ensure that the following privilege is enabled: Location services > Basemaps > Basemap styles service. Copy the access token as it will be used in the next step.
-
In Visual Studio, in the Solution Explorer, click App.xaml.cs.
-
In the App class, add an override for the
On
function to set theStartup() Api
property onKey ArcGISRuntimeEnvironment
.App.xaml.csUse dark colors for code blocks public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); Esri.ArcGISRuntime.ArcGISRuntimeEnvironment.ApiKey = "YOUR_ACCESS_TOKEN"; } } }
-
If you are developing with Visual Studio for Windows, ArcGIS Maps SDK for .NET provides a set of project templates for each supported .NET platform. These templates follow the Model-View-ViewModel (MVVM) design pattern. Install the ArcGIS Maps SDK for .NET Visual Studio Extension to add the templates to Visual Studio (Windows only). See Install and set up for details.
Update the tutorial name used in the project (optional)
The Visual Studio solution, project, and the namespace for all classes currently use the name DisplayAMap. Follow the steps below if you prefer the name to reflect the current tutorial. These steps are not required, your code will still work if you keep the original name.
The tutorial instructions and code use the name QueryAFeatureLayerSQL for the solution, project, and namespace. You can choose any name you like, but it should be the same for each of these.
-
Update the name for the solution and the project.
- In Visual Studio, in the Solution Explorer, right-click the solution name and choose Rename. Provide the new name for your solution.
- In the Solution Explorer, right-click the project name and choose Rename. Provide the new name for your project.
-
Rename the namespace used by classes in the project.
- In the Solution Explorer, expand the project node.
- Double-click MapViewModel.cs in the Solution Explorer to open the file.
- In the
Map
class, double-click the namespace name (View Model Display
) to select it, and then right-click and choose Rename....A Map - Provide the new name for the namespace.
- Click Apply in the Rename: DisplayAMap window that appears in the upper-right of the code window. This will rename the namespace throughout your project.
-
Build the project.
- Choose Build > Build solution (or press <F6>).
Steps
Add UI for selecting a predefined query expression
To make performing a query on a feature layer more flexible, add a Combo
control to present a list of predefined attribute queries for the parcels dataset. While editing this file, also modify the Map
control to bind its Selection
to a property in the view model (so you can set the color used to display selected parcels).
-
In the Visual Studio > Solution Explorer, double-click the MainWindow.xaml file to open it.
-
Add XAML that defines a
Combo
control and its behavior.Box - The control is positioned above the map view in the upper-left corner.
- A list of
Combo
s shows predefined expression choices.Box Item - The first combo box item instructs the user to choose an expression that will be selected when the app initializes.
- Changes in the selected expression will be handled by the
Query
event handler.Combo Box _Selection Changed
Also modify the
Map
control to bind theView Selection
property.Properties MainWindow.xamlUse dark colors for code blocks <Grid> <esri:MapView x:Name="MainMapView" Map="{Binding Map, Source={StaticResource MapViewModel}}" SelectionProperties="{Binding SelectionProps, Source={StaticResource MapViewModel}}"/> <ComboBox x:Name="QueryComboBox" SelectionChanged="QueryComboBox_SelectionChanged" SelectedIndex="0" SelectedValuePath="Content" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="20" Padding="30,10"> <ComboBoxItem>Choose a SQL where clause</ComboBoxItem> <ComboBoxItem>UseType = 'Government'</ComboBoxItem> <ComboBoxItem>UseType = 'Residential'</ComboBoxItem> <ComboBoxItem>UseType = 'Irrigated Farm'</ComboBoxItem> <ComboBoxItem>TaxRateArea = 10853</ComboBoxItem> <ComboBoxItem>TaxRateArea = 10860</ComboBoxItem> <ComboBoxItem>Roll_LandValue > 1000000</ComboBoxItem> <ComboBoxItem>Roll_LandValue < 1000000</ComboBoxItem> </ComboBox> </Grid>
-
In the section for the combo box you just added, right-click on the name of the event handler text ("QueryComboBox_SelectionChanged") and choose Go To definition from the context menu. Visual Studio will open the MapWindows.xaml.cs file with the stub for the new
Query
function.Combo Box _Selection Changed()
Add code to call the selected query for the current map extent
When the user chooses an expression in the combo box, call a function to execute the query.
The function to execute the query takes three arguments: the ID for the layer to query (string), a SQL expression that defines attribute criteria (string), and the area of the MapView
currently being viewed (Envelope
).
-
In the
Query
function: modify the method signature to add theCombo Box _Selection Changed() async
keyword.MainWindow.xaml.csUse dark colors for code blocks private async void QueryComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { }
-
Again, in the
Query
function: add code to gather the information required to perform the query, then call theCombo Box _Selection Changed() Query
function (that you will write in a coming step).Feature Layer MainWindow.xaml.csUse dark colors for code blocks private async void QueryComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { // Since the first choice in the combo box are instructions for the app // (not actual SQL where clause syntax), ignore it. if (QueryComboBox.SelectedIndex != 0) { // Get the view model using the ID given for the static resource in the XAML. var currentMapViewModel = this.FindResource("MapViewModel") as MapViewModel; // Get the current view point extent. var currentExtent = MainMapView?.GetCurrentViewpoint(ViewpointType.BoundingGeometry)?.TargetGeometry as Envelope; // Define the string ID for the feature layer to query. string featureLayerId = "Parcels"; // Define the SQL query where clause to apply to the feature layer. // Several SQL query strings were pre-populated in the combo box. // This line of code gets the selected choice from the combo box // and assigns it to the SQL query string. object selectedValue = QueryComboBox.SelectedValue; var sqlQuery = selectedValue?.ToString(); // Call the function in the view model that queries a feature layer. Pass in the: // (1) feature layer ID // (2) specific SQL syntax for the feature layer // (3) current map extent if (!string.IsNullOrEmpty(sqlQuery) && currentExtent != null) { await currentMapViewModel!.QueryFeatureLayer(featureLayerId, sqlQuery, currentExtent); } } }
Add the parcels layer to the map and set selection properties
You now need to begin working in a different code file within this project.
First, add the LA parcels FeatureLayer
to the map's collection of data layers (GeoModel.OperationalLayers
). Providing the Layer.Id
allows for referencing the parcels layer from the layer collection when needed. Define the selection color via the map view's SelectionProperties
to distinguish selected features in the map.
-
In the Visual Studio > Solution Explorer, double-click MapViewModel.cs to open the file.
The project uses the Model-View-ViewModel (MVVM) design pattern to separate the application logic (view model) from the user interface (view).
Map
contains the view model class for the application, calledView Model.cs Map
. See the Microsoft documentation for more information about the Model-View-ViewModel pattern.View Model -
Add additional required
using
statements at the top of the class. These make your code more concise and allow you to use classes from these namespaces without having to fully qualify them.MapViewModel.csUse dark colors for code blocks using System; using System.Collections.Generic; using System.Text; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using System.ComponentModel; using System.Runtime.CompilerServices; using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.UI; using System.Threading.Tasks;
-
Just after the section of code that defines the
Map
public property, create a similarSelection
public property as follows.Props MapViewModel.csUse dark colors for code blocks private SelectionProperties? _selectionProps; public SelectionProperties? SelectionProps { get { return _selectionProps; } set { _selectionProps = value; OnPropertyChanged(); } }
-
Add code to the
Setup
function that adds the parcels feature layer to the map and sets the selection properties.Map() MapViewModel.csUse dark colors for code blocks private void SetupMap() { // Create a new map with a 'topographic vector' basemap. Map = new Map(BasemapStyle.ArcGISTopographic); // Add a layer that shows parcels for Los Angeles County. Uri parcelsUri = new Uri("https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0"); FeatureLayer parcelsFeatureLayer = new FeatureLayer(parcelsUri); // Give the layer an ID so we can easily find it later, then add it to the map. parcelsFeatureLayer.Id = "Parcels"; Map.OperationalLayers.Add(parcelsFeatureLayer); // Create selection properties (bound to the MapView). SelectionProperties selectionProps = new SelectionProperties(); selectionProps.Color = System.Drawing.Color.Yellow; this.SelectionProps = selectionProps; }
Create a function to query the parcels layer and select the result
In this step, create a new function that queries a FeatureLayer
(identified using its ID) using both attribute and spatial criteria. After clearing any currently selected features, a new query will be executed to find features in the map's current extent that meet the selected attribute expression. The features in the FeatureQueryResult
will be selected in the parcels layer.
-
Add the following new method named
Query
just after theFeature Layer() Setup
method.Map() MapViewModel.csUse dark colors for code blocks public async Task QueryFeatureLayer(string layerId, string whereExpression, Envelope queryExtent) { // Get the layer based on its Id. var featureLayerToQuery = _map?.OperationalLayers[layerId] as FeatureLayer; // Get the feature table from the feature layer. var featureTableToQuery = featureLayerToQuery?.FeatureTable; if(featureTableToQuery == null) { return; } // Clear any existing selection. featureLayerToQuery?.ClearSelection(); // Create the query parameters using the where expression and extent passed in. QueryParameters queryParams = new QueryParameters { Geometry = queryExtent, ReturnGeometry = true, WhereClause = whereExpression, }; // Query the table and get the list of features in the result. var queryResult = await featureTableToQuery.QueryFeaturesAsync(queryParams); // Loop over each feature from the query result. foreach (Feature feature in queryResult) { // Select each feature. featureLayerToQuery!.SelectFeature(feature); } }
-
Click Debug > Start Debugging (or press <F5> on the keyboard) to run the app.
The app loads with the map centered on the Santa Monica Mountains in California with the parcels feature layer displayed. Choose an attribute expression, and parcels in the current extent that meet the selected criteria will display in the specified selection color.
What's next?
Learn how to use additional API features, ArcGIS location services, and ArcGIS tools in these tutorials: