Filter features displayed on a map using a definition expression or a display filter.

Use case
Definition queries allow you to define a subset of features to work with in a layer by filtering which features are retrieved from the dataset by the layer. This means that a definition query affects not only drawing, but also which features appear in the layer’s attribute table and therefore which features can be selected, labeled, identified, and processed by geoprocessing tools.
Alternatively, display filters limit which features are drawn, but retain all features in queries and when processing. Definition queries and display filters can be used together on a layer, but definition queries limit the features available in the layer, while display filters only limit which features are displayed.
In this sample you can filter a dataset of tree quality selecting for only those trees which require maintenance or are damaged.
How to use the sample
Press ‘Apply Expression’ to limit the features requested from the feature layer to those specified by the SQL query definition expression. Press ‘Apply Display Filter’ to limit the features shown on the feature layer to those specified by the SQL query without modifying the feature table. Click ‘Reset’ to remove the definition expression on the feature layer, which returns all the records.
How it works
- Create a service feature table from a URL.
- Create a feature layer from the service feature table.
- Filter features on your feature layer using a
DefinitionExpressionto view a subset of features and modify the attribute table. - Filter features on your feature layer using a
DisplayFilterto view a subset of features without modifying the attribute table.
Relevant API
- DefinitionExpression
- DisplayFilter
- FeatureLayer
- ServiceFeatureTable
About the data
This map displays point features related to crime incidents such as grafitti and tree damage that have been reported by city residents.
Tags
definition expression, display filter, filter, limit data, query, restrict data, SQL, where clause
Sample Code
// [WriteFile Name=FilterByDefinitionExpressionOrDisplayFilter, Category=Features]// [Legal]// Copyright 2016 Esri.//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.// [Legal]
#ifdef PCH_BUILD#include "pch.hpp"#endif // PCH_BUILD
// sample headers#include "FilterByDefinitionExpressionOrDisplayFilter.h"
// ArcGIS Maps SDK headers#include "Basemap.h"#include "DisplayFilter.h"#include "DisplayFilterDefinition.h"#include "FeatureLayer.h"#include "LayerListModel.h"#include "ManualDisplayFilterDefinition.h"#include "Map.h"#include "MapQuickView.h"#include "MapTypes.h"#include "MapViewTypes.h"#include "Point.h"#include "QueryParameters.h"#include "ServiceFeatureTable.h"#include "SpatialReference.h"#include "Viewpoint.h"
// Qt headers#include <QFuture>#include <QUrl>#include <QUuid>
using namespace Esri::ArcGISRuntime;
FilterByDefinitionExpressionOrDisplayFilter::FilterByDefinitionExpressionOrDisplayFilter(QQuickItem* parent) : QQuickItem(parent){}
FilterByDefinitionExpressionOrDisplayFilter::~FilterByDefinitionExpressionOrDisplayFilter() = default;
void FilterByDefinitionExpressionOrDisplayFilter::init(){ qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<FilterByDefinitionExpressionOrDisplayFilter>("Esri.Samples", 1, 0, "FilterByDefinitionExpressionOrDisplayFilterSample");}
void FilterByDefinitionExpressionOrDisplayFilter::componentComplete(){ QQuickItem::componentComplete();
//! [Obtain the instantiated map view in Cpp] // find QML MapView component m_mapView = findChild<MapQuickView*>("mapView"); m_mapView->setWrapAroundMode(WrapAroundMode::Disabled);
// Create a map using the topographic basemap m_map = new Map(BasemapStyle::ArcGISTopographic, this); const Point center = Point(-13630484, 4545415, SpatialReference(102100)); constexpr double scale = 300000.0; m_map->setInitialViewpoint(Viewpoint(center, scale));
// Set map to map view m_mapView->setMap(m_map); //! [Obtain the instantiated map view in Cpp]
// create the feature table m_featureTable = new ServiceFeatureTable(QUrl("https://sampleserver6.arcgisonline.com/arcgis/rest/services/SF311/FeatureServer/0"), this); // create the feature layer using the feature table m_featureLayer = new FeatureLayer(m_featureTable, this);
connect(m_featureLayer, &FeatureLayer::loadStatusChanged, this, [this](LoadStatus loadStatus) { loadStatus == LoadStatus::Loaded ? m_initialized = true : m_initialized = false;
// Initalize the feature count when the feature layer first loads queryFeatureCountInCurrentExtent(); emit layerInitializedChanged(); });
// add the feature layer to the map m_map->operationalLayers()->append(m_featureLayer);}
bool FilterByDefinitionExpressionOrDisplayFilter::layerInitialized() const{ return m_initialized;}
int FilterByDefinitionExpressionOrDisplayFilter::currentFeatureCount() const{ return m_currentFeatureCount;}
void FilterByDefinitionExpressionOrDisplayFilter::setDefExpression(const QString& whereClause){ // reset display filter parameters before setting definition expression parameters resetDisplayFilterParams();
m_featureLayer->setDefinitionExpression(whereClause);
// Feature count in the extent should not change with different definition expressions. // If the extent changes and user clicks the button to reapply definition expression // the feature count number will update to reflect the number of feature count in the new extent queryFeatureCountInCurrentExtent();}
void FilterByDefinitionExpressionOrDisplayFilter::setDisplayFilter(const QString& whereClause){ // reset definition expression parameters before setting display filter parameters resetDefExpressionParams();
DisplayFilter* displayFilter = new DisplayFilter("Damaged Trees", whereClause, this); const QList<DisplayFilter*> availableFilters{displayFilter};
ManualDisplayFilterDefinition* displayFilterDefinition = new ManualDisplayFilterDefinition(displayFilter, availableFilters, this); m_featureLayer->setDisplayFilterDefinition(displayFilterDefinition);
queryFeatureCountInCurrentExtent();}
void FilterByDefinitionExpressionOrDisplayFilter::queryFeatureCountInCurrentExtent(){ QueryParameters parameters; parameters.setGeometry(m_mapView->currentViewpoint(ViewpointType::BoundingGeometry).targetGeometry());
m_featureTable->queryFeatureCountAsync(parameters) .then(this, [this](int countResult) { m_currentFeatureCount = countResult; emit currentFeatureCountChanged(); });}
void FilterByDefinitionExpressionOrDisplayFilter::resetDisplayFilterParams(){ DisplayFilter* displayFilter = new DisplayFilter("No Filter", "1=1", this); const QList<DisplayFilter*> availableFilters{displayFilter};
ManualDisplayFilterDefinition* displayFilterDefinition = new ManualDisplayFilterDefinition(displayFilter, availableFilters, this); m_featureLayer->setDisplayFilterDefinition(displayFilterDefinition);
queryFeatureCountInCurrentExtent();}
void FilterByDefinitionExpressionOrDisplayFilter::resetDefExpressionParams(){ m_featureLayer->setDefinitionExpression("");
connect(m_mapView, &MapQuickView::drawStatusChanged, this, [this](DrawStatus drawStatus) { if (drawStatus == DrawStatus::Completed) { m_mapDrawing = false; queryFeatureCountInCurrentExtent(); } else { m_mapDrawing = true; }
emit mapDrawStatusChanged(); });}
bool FilterByDefinitionExpressionOrDisplayFilter::mapDrawing() const{ return m_mapDrawing;}// [WriteFile Name=FilterByDefinitionExpressionOrDisplayFilter, Category=Features]// [Legal]// Copyright 2016 Esri.//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.// [Legal]
#ifndef FILTER_BY_DEFINITION_EXPRESSION_OR_DISPLAY_FILTER_H#define FILTER_BY_DEFINITION_EXPRESSION_OR_DISPLAY_FILTER_H
// Qt headers#include <QQuickItem>
namespace Esri::ArcGISRuntime{ class Map; class MapQuickView; class FeatureLayer; class ServiceFeatureTable;} // namespace Esri::ArcGISRuntime
class FilterByDefinitionExpressionOrDisplayFilter : public QQuickItem{ Q_OBJECT
Q_PROPERTY(bool layerInitialized READ layerInitialized NOTIFY layerInitializedChanged) Q_PROPERTY(int currentFeatureCount READ currentFeatureCount NOTIFY currentFeatureCountChanged) Q_PROPERTY(bool mapDrawing READ mapDrawing NOTIFY mapDrawStatusChanged)
public: explicit FilterByDefinitionExpressionOrDisplayFilter(QQuickItem* parent = nullptr); ~FilterByDefinitionExpressionOrDisplayFilter() override;
void componentComplete() override; static void init(); Q_INVOKABLE void setDefExpression(const QString& whereClause); Q_INVOKABLE void setDisplayFilter(const QString& whereClause); Q_INVOKABLE void resetDisplayFilterParams(); Q_INVOKABLE void resetDefExpressionParams();
signals: void layerInitializedChanged(); void currentFeatureCountChanged(); void mapDrawStatusChanged();
private: bool layerInitialized() const; int currentFeatureCount() const; void queryFeatureCountInCurrentExtent(); bool mapDrawing() const;
private: Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr; Esri::ArcGISRuntime::FeatureLayer* m_featureLayer = nullptr; bool m_initialized = false; Esri::ArcGISRuntime::ServiceFeatureTable* m_featureTable = nullptr; int m_currentFeatureCount = 0; bool m_mapDrawing = false;};
#endif // FILTER_BY_DEFINITION_EXPRESSION_OR_DISPLAY_FILTER_H// [WriteFile Name=FilterByDefinitionExpressionOrDisplayFilter, Category=Features]// [Legal]// Copyright 2016 Esri.//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.// [Legal]
import QtQuickimport QtQuick.Controls//! [Import the namespace that has QML type that was registered in Cpp]import Esri.Samples
FilterByDefinitionExpressionOrDisplayFilterSample { id: definitionExpressionOrDisplayFilterSample width: 800 height: 600
//! [Declare map view in QML that will be accessed from Cpp] // add a mapView component MapView { anchors.fill: parent objectName: "mapView"
Component.onCompleted: { // Set the focus on MapView to initially enable keyboard navigation forceActiveFocus(); } } //! [Declare map view in QML that will be accessed from Cpp]
Column { id: expressionColumn anchors { bottom: parent.bottom left: parent.left right: parent.right margins: 5 bottomMargin: 25 } spacing: 5
Label { text: qsTr("Current feature count: " + definitionExpressionOrDisplayFilterSample.currentFeatureCount) color: "black" }
// button to apply a definition expression Button { text: qsTr("Apply Expression") enabled: definitionExpressionOrDisplayFilterSample.layerInitialized width: 200 onClicked: { // Call C++ invokable function to set the definition expression definitionExpressionOrDisplayFilterSample.setDefExpression("req_type = \'Tree Maintenance or Damage\'"); } }
// button to apply a display filter Button { text: qsTr("Apply Display Filter") enabled: definitionExpressionOrDisplayFilterSample.layerInitialized width: 200 onClicked: { // Call C++ invokable function to set the display filter definitionExpressionOrDisplayFilterSample.setDisplayFilter("req_type = \'Tree Maintenance or Damage\'"); } }
// button to reset the definition expression Button { text: qsTr("Reset") enabled: definitionExpressionOrDisplayFilterSample.layerInitialized width: 200 onClicked: { // Call C++ invokable function to reset the definition expression and display filter definitionExpressionOrDisplayFilterSample.resetDisplayFilterParams(); definitionExpressionOrDisplayFilterSample.resetDefExpressionParams(); } } }}// [WriteFile Name=FilterByDefinitionExpressionOrDisplayFilter, Category=Features]// [Legal]// Copyright 2015 Esri.//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.// [Legal]
// sample headers#include "FilterByDefinitionExpressionOrDisplayFilter.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"
// Qt headers#include <QCommandLineParser>#include <QDir>#include <QGuiApplication>#include <QQmlEngine>#include <QQuickView>#include <QSettings>
// Platform specific headers#ifdef Q_OS_WIN#include <Windows.h>#endif
#define STRINGIZE(x) #x#define QUOTE(x) STRINGIZE(x)
int main(int argc, char* argv[]){ QGuiApplication app(argc, argv); app.setApplicationName(QString("FilterByDefinitionExpressionOrDisplayFilter"));
// Use of ArcGIS location services, such as basemap styles, geocoding, and routing services, // requires an access token. For more information see // https://links.esri.com/arcgis-runtime-security-auth.
// The following methods grant an access token:
// 1. User authentication: Grants a temporary access token associated with a user's ArcGIS account. // To generate a token, a user logs in to the app with an ArcGIS account that is part of an // organization in ArcGIS Online or ArcGIS Enterprise.
// 2. API key authentication: Get a long-lived access token that gives your application access to // ArcGIS location services. Go to the tutorial at https://links.esri.com/create-an-api-key. // Copy the API Key access token.
const QString accessToken = QString("");
if (accessToken.isEmpty()) { qWarning() << "Use of ArcGIS location services, such as the basemap styles service, requires" << "you to authenticate with an ArcGIS account or set the API Key property."; } else { Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setApiKey(accessToken); }
// Initialize the sample FilterByDefinitionExpressionOrDisplayFilter::init();
/* Leaving this in for snippet purposes //! [Register the mapview for QML] // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); //! [Register the mapview for QML] //! */
// Initialize application view QQuickView view; view.setResizeMode(QQuickView::SizeRootObjectToView);
// Add the import Path view.engine()->addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml"));
QString arcGISRuntimeImportPath = QUOTE(ARCGIS_RUNTIME_IMPORT_PATH);
#if defined(LINUX_PLATFORM_REPLACEMENT) // on some linux platforms the string 'linux' is replaced with 1 // fix the replacement paths which were created QString replaceString = QUOTE(LINUX_PLATFORM_REPLACEMENT); arcGISRuntimeImportPath = arcGISRuntimeImportPath.replace(replaceString, "linux", Qt::CaseSensitive);#endif
// Add the Runtime and Extras path view.engine()->addImportPath(arcGISRuntimeImportPath);
// Set the source view.setSource(QUrl("qrc:/Samples/Features/FilterByDefinitionExpressionOrDisplayFilter/FilterByDefinitionExpressionOrDisplayFilter.qml"));
view.show();
return app.exec();}