Feature layer query

View inC++QMLView on GitHubSample viewer app

Find features in a feature table which match an SQL query.

screenshot

Use case

Query expressions can be used in ArcGIS to select a subset of features from a feature table. This is most useful in large or complicated data sets. A possible use case might be on a feature table marking the location of street furniture through a city. A user may wish to query by a TYPE column to return "benches". In this sample, we query a U.S. state by STATE_NAME from a feature table containing all U.S. states.

How to use the sample

Input the name of a U.S. state into the text field. When you click "Find and Select", a query is performed and the matching features are highlighted or an error is returned.

How it works

Enter part of a USA state name in the text box and select the Find and Select button. The sample uses the text from the text box to query for the state name, and will select the features returned from the query. Also, the map view will pan and zoom to the first feature in the list of selected features.

  1. Create a ServiceFeatureTable using the URL of a feature service.
  2. Create a QueryParameters with a where clause specified by setting whereClause.
  3. Perform the query using queryFeatures(query) on the service feature table.
  4. When complete, the query will return a FeatureQueryResult which can be iterated over to get the matching features.

Relevant API

  • FeatureLayer
  • FeatureQueryResult
  • QueryParameters
  • ServiceFeatureTable

About the data

This sample uses U.S. State polygon features from the USA 2016 Daytime Population feature service.

Tags

Search and Query

Sample Code

FeatureLayer_Query.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
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
198
199
200
// [WriteFile Name=FeatureLayer_Query, 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 QtQuick 2.6
import QtQuick.Controls 2.2
import Esri.ArcGISRuntime 100.15

Rectangle {
    width: 800
    height: 600

    // Map view UI presentation at top
    MapView {
        id: mapView

        anchors.fill: parent
        wrapAroundMode: Enums.WrapAroundModeDisabled

        Component.onCompleted: {
            // Set the focus on MapView to initially enable keyboard navigation
            forceActiveFocus();
        }

        Map {
            id: map

            Basemap {
                initStyle: Enums.BasemapStyleArcGISTopographic
            }
            initialViewpoint: viewPoint

            FeatureLayer {
                id: featureLayer
                maxScale: 10000

                // default property (renderer)
                SimpleRenderer {
                    SimpleFillSymbol {
                        style: Enums.SimpleFillSymbolStyleSolid
                        color: Qt.rgba(1, 1, 0, 0.6)

                        // default property (outline)
                        SimpleLineSymbol {
                            style: Enums.SimpleLineSymbolStyleSolid
                            color: "black"
                            width: 2.0
                            antiAlias: true
                        }
                    }
                }

                // feature table
                ServiceFeatureTable {
                    id: featureTable
                    url: "https://services.arcgis.com/jIL9msH9OI208GCb/arcgis/rest/services/USA_Daytime_Population_2016/FeatureServer/0"
                }
            }
        }

        // initial viewPoint
        ViewpointCenter {
            id: viewPoint
            center: Point {
                x: -11e6
                y: 5e6
                spatialReference: SpatialReference {
                    wkid: 102100
                }
            }
            targetScale: 9e7
        }

        Row {
            id: findRow

            anchors {
                top: parent.top
                bottom: map.top
                left: parent.left
                right: parent.right
                margins: 5
            }
            spacing: 5

            TextField {
                id: findText
                width: parent.width * 0.25
                placeholderText: "Enter a state name to select"
                inputMethodHints: Qt.ImhNoPredictiveText
                selectByMouse: true
                validator: RegExpValidator{ regExp: /^[a-zA-Z ]*$/ }
                Keys.onReturnPressed: {
                    btn.clicked();
                }
            }

            Button {
                id: btn
                text: "Find and Select"
                enabled: featureTable.loadStatus === Enums.LoadStatusLoaded
                onClicked: {
                    const queryString = `LOWER(STATE_NAME) LIKE LOWER('${findText.text}%')`;
                    queryFeatures(queryString, featureTable) // query the table
                    .then(result=>selectResults(result, featureLayer)) // then select the features
                    .then(features=>mapView.setViewpointGeometryAndPadding(features[0].geometry, 30)) // then zoom to the select feature
                    .catch(error=>textLabel.text = error.message);
                }
            }
        }

        Dialog {
            id: errorMsgDialog
            modal: true
            x: Math.round(parent.width - width) / 2
            y: Math.round(parent.height - height) / 2
            standardButtons: Dialog.Ok
            property alias text : textLabel.text
            Text {
                id: textLabel
                onTextChanged: {
                    if (text.length > 0)
                        errorMsgDialog.open();
                }
            }
        }
    }

    function selectResults(result, layer) {
        return new Promise(
                    (resolve, reject)=>{
                        // clear any previous selection
                        layer.clearSelection();

                        // get the features
                        const features = Array.from(result.iterator.features);
                        if (features.length === 0) {
                            const msg = "No state named " + findText.text.toUpperCase() + " exists."
                            reject({message: msg});
                        }

                        // select the features
                        // The ideal way to select features is to call featureLayer.selectFeaturesWithQuery(), which will
                        // automatically select the features based on your query.  This is just a way to show you operations
                        // that you can do with query results. Refer to API doc for more details.
                        layer.selectFeatures(features);

                        resolve(features)
                    });
    }


    function queryFeatures(searchString, table){
        return new Promise(
                    (resolve, reject)=>{
                        let taskId;
                        let parameters = ArcGISRuntimeEnvironment.createObject("QueryParameters");
                        parameters.whereClause = searchString;

                        const featureStatusChanged = ()=> {
                            switch (table.queryFeaturesStatus) {
                                case Enums.TaskStatusCompleted:
                                    table.queryFeaturesStatusChanged.disconnect(featureStatusChanged);
                                    const result = table.queryFeaturesResults[taskId];
                                    if (result) {
                                        resolve(result);
                                    } else {
                                        reject({message: "The query finished but there was no result for this taskId", taskId: taskId});
                                    }
                                    break;
                                case Enums.TaskStatusErrored:
                                    table.queryFeaturesStatusChanged.disconnect(featureStatusChanged);
                                    if (table.error) {
                                        reject(table.error);
                                    } else {
                                        reject({message: table.tableName + ": query task errored++++"});
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }

                        table.queryFeaturesStatusChanged.connect(featureStatusChanged);
                        taskId = table.queryFeatures(parameters);
                    });
    }
}

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