Statistical query

View inC++QMLView on GitHubSample viewer app

Query a table to get aggregated statistics back for a specific field.

screenshot

Use case

For example, a county boundaries table with population information can be queried to return aggregated results for total, average, maximum, and minimum population, rather than downloading the values for every county and calculating statistics manually.

How to use the sample

Pan and zoom to define the extent for the query. Use the 'Cities in current extent' checkbox to control whether the query only includes features in the visible extent. Use the 'Cities grater than 5M' checkbox to filter the results to only those cities with a population greater than 5 million people. Click 'Get statistics' to perform the query. The query will return population-based statistics from the combined results of all features matching the query criteria.

How it works

  1. Create a ServiceFeatureTable with a URL to the feature service.
  2. Create StatisticsQueryParameters, and StatisticDefinition objects, and add to the parameters.
  3. Execute queryStatistics on the ServiceFeatureTable. Depending on the state of the two checkboxes, additional parameters are set.
  4. Display each StatisticRecord in the first returned QueryStatisticsResult.

Relevant API

  • QueryParameters
  • ServiceFeatureTable
  • StatisticDefinition
  • StatisticRecord
  • StatisticsQueryParameters
  • StatisticsQueryResult
  • StatisticType

Tags

analysis, average, bounding geometry, filter, intersect, maximum, mean, minimum, query, spatial query, standard deviation, statistics, sum, variance

Sample Code

StatisticalQuery.cppStatisticalQuery.cppStatisticalQuery.hStatisticalQuery.qml
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
// [WriteFile Name=StatisticalQuery, Category=Analysis]
// [Legal]
// Copyright 2017 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

#include "StatisticalQuery.h"

#include "Map.h"
#include "MapQuickView.h"
#include "ArcGISVectorTiledLayer.h"
#include "FeatureLayer.h"
#include "ServiceFeatureTable.h"
#include "StatisticalQuery.h"
#include "StatisticsQueryParameters.h"
#include "StatisticDefinition.h"
#include "StatisticRecord.h"
#include "StatisticRecordIterator.h"
#include "Viewpoint.h"

#include <memory>
#include <QUrl>

using namespace Esri::ArcGISRuntime;

StatisticalQuery::StatisticalQuery(QQuickItem* parent /* = nullptr */):
  QQuickItem(parent)
{
}

void StatisticalQuery::init()
{
  // Register the map view for QML
  qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView");
  qmlRegisterType<StatisticalQuery>("Esri.Samples", 1, 0, "StatisticalQuerySample");
}

void StatisticalQuery::componentComplete()
{
  QQuickItem::componentComplete();

  // find QML MapView component
  m_mapView = findChild<MapQuickView*>("mapView");

  // Create a new Map with the world streets vector basemap
  m_map = new Map(BasemapStyle::ArcGISStreets, this);

  // Create feature table using the world cities URL
  m_featureTable = new ServiceFeatureTable(QUrl("https://sampleserver6.arcgisonline.com/arcgis/rest/services/SampleWorldCities/MapServer/0"), this);

  // Create a new feature layer to display features in the world cities table
  FeatureLayer* featureLayer = new FeatureLayer(m_featureTable, this);
  m_map->operationalLayers()->append(featureLayer);

  // Set map to map view
  m_mapView->setMap(m_map);

  connect(m_featureTable, &ServiceFeatureTable::errorOccurred, this, [this](Error e)
  {
    if (e.isEmpty())
      return;

    emit showStatistics(e.message());
  });

  // connect to queryStatisticsCompleted
  connect(m_featureTable, &ServiceFeatureTable::queryStatisticsCompleted, this, [this](QUuid, StatisticsQueryResult* rawResult)
  {
    if (!rawResult)
      return;

    // Delete rawResult when we leave local scope.
    auto result = std::unique_ptr<StatisticsQueryResult>(rawResult);

    // Iterate through the results
    QObject parent;
    QString resultText;
    StatisticRecordIterator iter = result->iterator();
    while (iter.hasNext())
    {
      StatisticRecord* record = iter.next(&parent);
      const QVariantMap& statsMap = record->statistics();
      for (auto it = statsMap.cbegin(); it != statsMap.cend(); ++it)
      {
        resultText += QString("%1: %2\n").arg(it.key(), it.value().toString());
      }
    }

    // Display the Results
    emit showStatistics(resultText);
  });
}

void StatisticalQuery::queryStatistics(bool extentOnly, bool bigCitiesOnly)
{
  // create the parameters
  StatisticsQueryParameters queryParameters;

  // Add the Statistic Definitions
  QList<StatisticDefinition> definitions
  {
    StatisticDefinition("POP", StatisticType::Average, ""),
    StatisticDefinition("POP", StatisticType::Minimum, ""),
    StatisticDefinition("POP", StatisticType::Maximum, ""),
    StatisticDefinition("POP", StatisticType::Sum, ""),
    StatisticDefinition("POP", StatisticType::StandardDeviation, ""),
    StatisticDefinition("POP", StatisticType::Variance, ""),
    StatisticDefinition("POP", StatisticType::Count, "CityCount")
  };
  queryParameters.setStatisticDefinitions(definitions);

  // If only using features in the current extent, set up the spatial filter for the statistics query parameters
  if (extentOnly)
  {
    // Set the statistics query parameters geometry with the envelope
    queryParameters.setGeometry(m_mapView->currentViewpoint(ViewpointType::BoundingGeometry).targetGeometry());

    // Set the spatial relationship to Intersects (which is the default)
    queryParameters.setSpatialRelationship(SpatialRelationship::Intersects);
  }

  // If only evaluating the largest cities (over 5 million in population), set up an attribute filter
  if (bigCitiesOnly)
    queryParameters.setWhereClause("POP_RANK = 1");

  // Execute the statistical query with these parameters
  m_featureTable->queryStatistics(queryParameters);
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.