Basic Querying in FeatureLayer

This sample demonstrates how to query on a FeatureLayer through crime data in San Francisco by using the queryFeatures() method. This allows the user to set the query parameters and shows the response of the query through the corresponding Popup.

How it works

When the application starts, the UI displays query options, either a basic query or query by distance. The query is called based on where the user clicks on the map. After a location is clicked in the application, this function is called. The FeatureLayer has many methods used to perform queries on its data. The queryFeatures() method allows the user to query features in the FeatureLayer based on an input query object. This method returns a FeatureSet Promise which can be accessed using .then().

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
function queryFeatures(screenPoint) {
  const point = view.toMap(screenPoint);
  layer.queryFeatures({
    //query object
    geometry: point,
    spatialRelationship: "intersects",
    returnGeometry: false,
    outFields: ["*"],
  })
  .then((featureSet) => {
    // set graphic location to mouse pointer and add to mapview
    pointGraphic.geometry = point;
    view.graphics.add(pointGraphic);
    // open popup of query result
    view.openPopup({
      location: point,
      features: featureSet.features
    });
  });
}

If the user selects 'Query By Distance', two parameters, distance and units, are added to the query object that is the input for layer.queryFeatures(), returning any item in the feature that is within 0.5 miles from where the user clicked on the map. The first feature that is highlighted will not necessarily be the same as the feature originally clicked on, but each feature resulting from the query can be viewed by clicking through the arrows at the bottom of the popup.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
layer.queryFeatures({
  geometry: point,
  // distance and units will be null if basic query selected
  distance: 0.5,
  units: "miles",
  spatialRelationship: "intersects",
  returnGeometry: false,
  outFields: ["*"],
})

See also Query features from a FeatureLayer.

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