Query feature count and extent

View inWPFUWPFormsiOSAndroid
View on GitHub

Zoom to features matching a query and count the features in the current visible extent.

Image of query feature count and extent

Use case

Queries can be used to search for features in a feature table using text entry. This is helpful for finding a specific feature by name in a large feature table. A query can also be used to count features in an extent. This could be used to count the number of a traffic incidents in a particular region when working with an incident dataset for a larger area.

How to use the sample

Use the button to zoom to the extent of the state specified (by abbreviation) in the textbox or use the button to count the features in the current extent.

How it works

Querying by state abbreviation:

  1. A QueryParameters object is created with a WhereClause.
  2. FeatureTable.QueryExtentAsync is called with the QueryParameters object to obtain the extent that contains all matching features.
  3. The extent is converted to a Viewpoint, which is passed to MapView.SetViewpointAsync.

Counting features in the current extent:

  1. The current visible extent is obtained from a call to MapView.GetCurrentViewpoint(ViewpointType).
  2. A QueryParameters object is created with the visible extent and a defined SpatialRelationship (in this case 'intersects').
  3. The count of matching features is obtained from a call to FeatureTable.QueryFeatureCountAsync.

Relevant API

  • FeatureTable.QueryExtentAsync
  • FeatureTable.QueryFeatureCountAsync
  • MapView.GetCurrentViewpoint(ViewpointType)
  • QueryParameters
  • QueryParameters.Geometry
  • QueryParameters.SpatialRelationship
  • QueryParameters.WhereClause

About the data

See the Medicare Hospital Spending per Patient, 2016 layer on ArcGIS Online.

Hospitals in blue/turquoise spend less than the national average. Red/salmon indicates higher spending relative to other hospitals, while gray is average.

Tags

count, feature layer, feature table, features, filter, number, query

Sample Code

QueryFeatureCountAndExtent.cs
                                                                                                                                                                                                     
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
// Copyright 2018 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.

using Android.App;
using Android.OS;
using Android.Widget;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using Android.Views;
using Android.Views.InputMethods;

namespace ArcGISRuntime.Samples.QueryFeatureCountAndExtent
{
    [Activity (ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        name: "Query feature count and extent",
        category: "Analysis",
        description: "Zoom to features matching a query and count the features in the current visible extent.",
        instructions: "Use the button to zoom to the extent of the state specified (by abbreviation) in the textbox or use the button to count the features in the current extent.",
        tags: new[] { "count", "feature layer", "feature table", "features", "filter", "number", "query" })]
    public class QueryFeatureCountAndExtent : Activity
    {
        // UI controls.
        private EditText _myStateEntry;
        private TextView _myResultsLabel;
        private Button _myQueryStateButton;
        private Button _myQueryExtentButton;
        private MapView _myMapView;

        // URL to the feature service.
        private readonly Uri _medicareHospitalSpendLayer =
            new Uri("https://services1.arcgis.com/4yjifSiIG17X0gW4/arcgis/rest/services/Medicare_Hospital_Spending_per_Patient/FeatureServer/0");

        // Feature table to query.
        private ServiceFeatureTable _featureTable;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            Title = "Query feature count and extent";

            CreateLayout();
            Initialize();
        }

        private async void Initialize()
        {
            // Create the map with a basemap.
            Map myMap = new Map(BasemapStyle.ArcGISDarkGray);

            // Create the feature table from the service URL.
            _featureTable = new ServiceFeatureTable(_medicareHospitalSpendLayer);

            // Create the feature layer from the table.
            FeatureLayer myFeatureLayer = new FeatureLayer(_featureTable);

            // Add the feature layer to the map.
            myMap.OperationalLayers.Add(myFeatureLayer);

            try
            {
                // Wait for the feature layer to load.
                await myFeatureLayer.LoadAsync();

                // Set the map initial extent to the extent of the feature layer.
                myMap.InitialViewpoint = new Viewpoint(myFeatureLayer.FullExtent);

                // Add the map to the MapView.
                _myMapView.Map = myMap;
            }
            catch (Exception e)
            {
                new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show();
            }
        }

        private async void BtnZoomToFeatures_Click(object sender, EventArgs e)
        {
            // Create the query parameters.
            QueryParameters queryStates = new QueryParameters { WhereClause = $"upper(State) LIKE '%{_myStateEntry.Text.ToUpper()}%'" };

            try
            {
                // Get the extent from the query.
                Envelope resultExtent = await _featureTable.QueryExtentAsync(queryStates);

                // Return if there is no result (might happen if query is invalid).
                if (resultExtent?.SpatialReference == null)
                {
                    _myResultsLabel.Text = $"Couldn't zoom to features in {_myStateEntry.Text}.";
                    return;
                }

                // Create a viewpoint from the extent.
                Viewpoint resultViewpoint = new Viewpoint(resultExtent);

                // Zoom to the viewpoint.
                await _myMapView.SetViewpointAsync(resultViewpoint);

                // Update label.
                _myResultsLabel.Text = $"Zoomed to features in {_myStateEntry.Text}.";
            }
            catch (Exception ex)
            {
                new AlertDialog.Builder(this).SetMessage(ex.ToString()).SetTitle("Error").Show();
            }
        }

        private async void BtnCountFeatures_Click(object sender, EventArgs e)
        {
            try
            {
                // Get the current visible extent.
                Geometry currentExtent = _myMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry;

                // Create the query parameters.
                QueryParameters queryCityCount = new QueryParameters
                {
                    Geometry = currentExtent,
                    // Specify the interpretation of the Geometry query parameters.
                    SpatialRelationship = SpatialRelationship.Intersects
                };

                // Get the count of matching features.
                long count = await _featureTable.QueryFeatureCountAsync(queryCityCount);

                // Update the UI.
                _myResultsLabel.Text = $"{count} features in extent";
            }
            catch (NullReferenceException exception)
            {
                // Sample wasn't ready.
                System.Diagnostics.Debug.WriteLine(exception);
            }
            catch (Exception)
            {
                // Uncaught exception in async void will crash application.
            }
        }

        private void CreateLayout()
        {
            // Create a new vertical layout for the app.
            LinearLayout layout = new LinearLayout(this) { Orientation = Orientation.Vertical };

            // Create the entry.
            _myStateEntry = new EditText(this) { Hint = "State abbreviation (e.g. NY)" };

            // Hide the keyboard on enter.
            _myStateEntry.KeyPress += (sender, args) =>
            {
                if (args.Event.Action == KeyEventActions.Down && args.KeyCode == Keycode.Enter)
                {
                    InputMethodManager imm = (InputMethodManager)GetSystemService(InputMethodService);
                    imm.HideSoftInputFromWindow(_myStateEntry.WindowToken, 0);
                    BtnZoomToFeatures_Click(_myStateEntry, null);
                }
                else
                {
                    args.Handled = false;
                }
            };

            // Create the results label.
            _myResultsLabel = new TextView(this);

            // Create the two buttons.
            _myQueryStateButton = new Button(this) { Text = "Zoom to matching features" };
            _myQueryExtentButton = new Button(this) { Text = "Count features in extent" };

            // Subscribe to button events.
            _myQueryExtentButton.Click += BtnCountFeatures_Click;
            _myQueryStateButton.Click += BtnZoomToFeatures_Click;

            // Add the views to the layout.
            layout.AddView(_myStateEntry);
            layout.AddView(_myQueryStateButton);
            layout.AddView(_myQueryExtentButton);
            layout.AddView(_myResultsLabel);
            _myMapView = new MapView(this);
            layout.AddView(_myMapView);

            // Show the layout in the app.
            SetContentView(layout);
        }
    }
}

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