Query data from an OGC API feature service using CQL filters.

Use case
CQL (Common Query Language) is an OGC-created query language used to query for subsets of features. Use CQL filters to narrow geometry results from an OGC feature table.
How to use the sample
The sample loads displaying a maximum of 1000 features within the OGC API feature service. Select a sample CQL query from the drop down menu. Optionally, adjust the max features value in the text box, and enter a date range such as June 13, 2011 (06/13/2011) to January 7, 2012 (01/07/2012) to narrow down the results based on time extent. Press the “Query” button to see the query applied to the OGC API features shown on the map.
How it works
- Create an
OgcFeatureCollectionTableobject using a URL to an OGC API feature service and a collection ID. - Create
QueryParametersand set a CQL filter string to it usingqueryParameters.setWhereClause(). - Set the maximum amount of features to be returned with
queryParamters.setMaxFeatures(). - Create a new
TimeExtentfrom start and end date values, and set it to thequeryParameters.setTimeExtent()method. - Populate the OGC feature collection table using
populateFromServiceAsync()with the customQueryParameterscreated in the previous steps. - Use
mapView.setViewpointGeometryAsync()with the OGC feature collection table extent to view the newly-queried features.
Relevant API
- OgcFeatureCollectionTable
- QueryParameters
- TimeExtent
About the data
The Daraa, Syria test data is OpenStreetMap data converted to the Topographic Data Store schema of NGA.
Additional information
See the OGC API website for more information on the OGC API family of standards. See the CQL documentation to learn more about the common query language.
Tags
browse, catalog, common query language, CQL, feature table, filter, OGC, OGC API, query, service, web
Sample Code
// [WriteFile Name=Query_OGC, Category=Layers]// [Legal]// Copyright 2021 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 "QueryOGCAPICQLFilters.h"
// ArcGIS Maps SDK headers#include "FeatureLayer.h"#include "GeodatabaseTypes.h"#include "LayerListModel.h"#include "Map.h"#include "MapQuickView.h"#include "MapTypes.h"#include "OgcFeatureCollectionTable.h"#include "QueryParameters.h"#include "SimpleLineSymbol.h"#include "SimpleRenderer.h"#include "SymbolTypes.h"#include "TimeExtent.h"#include "Viewpoint.h"
// Qt headers#include <QDateTime>#include <QFuture>
using namespace Esri::ArcGISRuntime;
QueryOGCAPICQLFilters::QueryOGCAPICQLFilters(QObject* parent /* = nullptr */): QObject(parent), m_map(new Map(BasemapStyle::ArcGISTopographic, this)){ const QUrl serviceUrl = QUrl("https://demo.ldproxy.net/daraa"); const QString collectionId = "TransportationGroundCrv"; m_ogcFeatureCollectionTable = new OgcFeatureCollectionTable(serviceUrl, collectionId, this);
// FeatureRequestMode::ManualCache specifies that features from the server will be stored locally for display and querying // In this mode, ServiceFeatureTable::populateFromService() must be called to populate the local cache m_ogcFeatureCollectionTable->setFeatureRequestMode(FeatureRequestMode::ManualCache);
// m_ogcFeatureCollectionTable->load() will be automatically called when added to a FeatureLayer m_featureLayer = new FeatureLayer(m_ogcFeatureCollectionTable, this);
m_map->operationalLayers()->append(m_featureLayer);
// Set a renderer to it to visualize the OGC API features and zoom to features m_featureLayer->setRenderer(new SimpleRenderer(new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, Qt::darkMagenta, 3, this), this));}
QueryOGCAPICQLFilters::~QueryOGCAPICQLFilters() = default;
void QueryOGCAPICQLFilters::init(){ // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<QueryOGCAPICQLFilters>("Esri.Samples", 1, 0, "QueryOGCAPICQLFiltersSample");}
MapQuickView* QueryOGCAPICQLFilters::mapView() const{ return m_mapView;}
// Set the view (created in QML)void QueryOGCAPICQLFilters::setMapView(MapQuickView* mapView){ if (!mapView || mapView == m_mapView) return;
m_mapView = mapView; m_mapView->setMap(m_map); m_mapView->setViewpointAsync(Viewpoint(32.62, 36.10, 200'000));
QueryParameters queryParams;
//Get the extent of the dataset m_dataSetExtent = m_ogcFeatureCollectionTable->extent(); queryParams.setGeometry(m_dataSetExtent); queryParams.setWhereClause("F_CODE = 'AP010'"); queryParams.setMaxFeatures(1000);
// Populate the feature collection table with features that match the parameters, clear the cache, and store all table fields auto future = m_ogcFeatureCollectionTable->populateFromServiceAsync(queryParams, true, {}); Q_UNUSED(future)
emit mapViewChanged();}
void QueryOGCAPICQLFilters::query(const QString& whereClause, const QString& maxFeature, const QString& fromDateString, const QString& toDateString){ if (!m_ogcFeatureCollectionTable || !m_featureLayer || !m_mapView) return;
// create the parameters QueryParameters queryParams;
queryParams.setGeometry(m_mapView->currentViewpoint(ViewpointType::BoundingGeometry).targetGeometry().extent()); queryParams.setWhereClause(whereClause); queryParams.setMaxFeatures(maxFeature.toUInt());
if (!fromDateString.isEmpty() && !toDateString.isEmpty()) { const QDateTime fromDate = QDateTime::fromString(fromDateString,"MM/dd/yyyy"); const QDateTime toDate = QDateTime::fromString(toDateString,"MM/dd/yyyy"); const TimeExtent timeExtent(fromDate.toUTC(), toDate.toUTC()); queryParams.setTimeExtent(timeExtent); }
// Populate the feature collection table with features that match the parameters, // clear the cache to prepare for the new query results, and store all table fields auto future = m_ogcFeatureCollectionTable->populateFromServiceAsync(queryParams, true, {}); Q_UNUSED(future)}// [WriteFile Name=QueryOGCAPICQLFiltersQuery_OGC, Category=Layers]// [Legal]// Copyright 2021 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 QUERYOGCAPICQLFILTERS_H#define QUERYOGCAPICQLFILTERS_H
// ArcGIS Maps SDK headers#include "Envelope.h"
// Qt headers#include <QObject>
namespace Esri::ArcGISRuntime{class FeatureLayer;class Map;class MapQuickView;class OgcFeatureCollectionTable;}
Q_MOC_INCLUDE("MapQuickView.h")
class QueryOGCAPICQLFilters : public QObject{ Q_OBJECT
Q_PROPERTY(Esri::ArcGISRuntime::MapQuickView* mapView READ mapView WRITE setMapView NOTIFY mapViewChanged)
public: explicit QueryOGCAPICQLFilters(QObject* parent = nullptr); ~QueryOGCAPICQLFilters();
static void init(); Q_INVOKABLE void query(const QString& whereClause, const QString& maxFeature, const QString& fromDateString, const QString& toDateString);
signals: void mapViewChanged();
private: Esri::ArcGISRuntime::MapQuickView* mapView() const; void setMapView(Esri::ArcGISRuntime::MapQuickView* mapView);
Esri::ArcGISRuntime::Envelope m_dataSetExtent; Esri::ArcGISRuntime::FeatureLayer* m_featureLayer = nullptr; Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr; Esri::ArcGISRuntime::OgcFeatureCollectionTable* m_ogcFeatureCollectionTable = nullptr;};
#endif // QUERYOGCAPICQLFILTERS_H// [WriteFile Name=Query_OGC, Category=Layers]// [Legal]// Copyright 2021 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.Controlsimport Esri.Samples
Item {
// add a mapView component MapView { id: view anchors.fill: parent }
// Declare the C++ instance which creates the map etc. and supply the view QueryOGCAPICQLFiltersSample { id: model mapView: view }
Rectangle { anchors { fill: controlColumn margins: -5 } color: "#efefef" radius: 5 border { color: "darkgray" width: 1 } }
Column { id: controlColumn anchors { left: parent.left top: parent.top margins: 10 } spacing: 5
Row { spacing: 5 Text { id: whereClauseText anchors.verticalCenter: parent.verticalCenter text: "Where Clause" }
ComboBox { id: whereClauseMenu width: 200 model: ["F_CODE = 'AP010'", "{ \"op\": \"=\", \"args\": [ { \"property\": \"F_CODE\" }, \"AP010\" ] }", "F_CODE LIKE 'AQ%'", "{\"op\": \"and\", \"args\":[{ \"op\": \"=\", \"args\":[{ \"property\" : \"F_CODE\" }, \"AP010\"]}, { \"op\": \"t_before\", \"args\":[{ \"property\" : \"ZI001_SDV\"},\"2013-01-01\"]}]}"] } }
Row { spacing: 8 Text { id: maxFeatureText anchors.verticalCenter: parent.verticalCenter text: "Max Features" }
TextField { id: maxFeatureField anchors.verticalCenter: parent.verticalCenter width: 200 text: "1000" selectByMouse: true validator: IntValidator {} } }
Row { spacing: 8 Text { id: fromField anchors.verticalCenter: parent.verticalCenter text: "From" rightPadding: 40 }
TextField { id: fromDate anchors.verticalCenter: parent.verticalCenter width: 200 text: "" selectByMouse: true validator: RegularExpressionValidator { regularExpression: /(0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01])[/](19|20)\d\d/ } placeholderText: "MM/DD/YYYY" } }
Row { spacing: 8 Text { id: toField anchors.verticalCenter: parent.verticalCenter text: "To" rightPadding: 53 }
TextField { id: toDate anchors.verticalCenter: parent.verticalCenter width: 200 text: "" selectByMouse: true validator: RegularExpressionValidator { regularExpression: /(0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01])[/](19|20)\d\d/ } placeholderText: "MM/DD/YYYY" } }
Button { anchors.horizontalCenter: parent.horizontalCenter text: "Query" onClicked: { model.query(whereClauseMenu.currentText, maxFeatureField.text, fromDate.text, toDate.text); } } }}// [Legal]// Copyright 2021 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 "QueryOGCAPICQLFilters.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"
// Qt headers#include <QCommandLineParser>#include <QDir>#include <QGuiApplication>#include <QQmlApplicationEngine>
// Platform specific headers#ifdef Q_OS_WIN#include <Windows.h>#endif
int main(int argc, char *argv[]){ Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setUseLegacyAuthentication(false); QGuiApplication app(argc, argv); app.setApplicationName(QString("QueryOGCAPICQLFilters"));
// 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 QueryOGCAPICQLFilters::init();
// Initialize application view QQmlApplicationEngine engine; // Add the import Path engine.addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml"));
#ifdef ARCGIS_RUNTIME_IMPORT_PATH_2 engine.addImportPath(ARCGIS_RUNTIME_IMPORT_PATH_2);#endif
// Set the source engine.load(QUrl("qrc:/Samples/Layers/QueryOGCAPICQLFilters/main.qml"));
return app.exec();}// Copyright 2021 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.
import QtQuick.Controlsimport Esri.Samples
ApplicationWindow { visible: true width: 800 height: 600
QueryOGCAPICQLFilters { anchors.fill: parent }}