Learn how to perform a spatial query to a feature service
A feature layer
In this tutorial, you use the OpenLayers Draw interaction to sketch a feature
Prerequisites
You need an ArcGIS Location Platform or ArcGIS Online account.
Steps
Get the starter app
Select a type of authentication and follow the steps to create a new app.
Choose API key authentication if you:
- Want the easiest way to get started.
- Want to build public applications
A public application is an application that allows anonymous access without requiring users to sign in with an ArcGIS account. It supports API key or app authentication. that access ArcGIS Location ServicesArcGIS Location Services, also referred to as Location Services, are services hosted by Esri that provide geospatial functionality for developing mapping applications. They include the ArcGIS Basemap Styles service, ArcGIS Static Basemap Tiles service, ArcGIS Places service, ArcGIS Geocoding service, ArcGIS Routing service, ArcGIS GeoEnrichment service, and ArcGIS Elevation service. An ArcGIS Location Platform or ArcGIS Online account is required to use the services. and secure itemsAn item, also known as a content item, is a resource stored in a portal such as a web map, hosted layer, style, script tool, file, or notebook. . - Have an ArcGIS Location Platform or ArcGIS Online account.
Choose user authentication if you:
- Want to build private applications.
- Require application users to sign in with their own ArcGIS account
An ArcGIS account is an identity with a user type and set of privileges that can access specific ArcGIS products, tools, APIs, services, and resources. The main account types that can be used for development are an ArcGIS Location Platform account, ArcGIS Online account, and ArcGIS Enterprise account. ArcGIS Location Platform and ArcGIS Online accounts are also associated with a subscription. and access resources their behalf. - Have an ArcGIS Online account.
To learn more about both types of authentication, go to Authentication.
Set up authentication
Set developer credentials
Use the API key or OAuth developer credentials
Add references
This tutorial uses ArcGIS REST JS to access a feature layer
-
In the
<headelement, add references to the ArcGIS REST JS and ol-popup libraries.> Use dark colors for code blocks <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@v10.9.0/ol.css"> <script src="https://cdn.jsdelivr.net/npm/ol@v10.9.0/dist/ol.js"></script> <script src="https://cdn.jsdelivr.net/npm/ol-mapbox-style@13.4.1/dist/olms.js"></script> <script src="https://unpkg.com/@esri/arcgis-rest-request@4/dist/bundled/request.umd.js"></script> <script src="https://unpkg.com/@esri/arcgis-rest-feature-service@4/dist/bundled/feature-service.umd.js"></script> <script src="https://unpkg.com/ol-popup@5.1.1/dist/ol-popup.js"></script> <link rel="stylesheet" href="https://unpkg.com/ol-popup@5.1.1/src/ol-popup.css">
Add layers
You will need two Vector layers. interaction will display the query polygon while the user is drawing it. Once the query returns, parcel will display the individual property parcels in the default style. Each contains a Vector source that initially contains no features.
In order to be able to draw shapes, you create a Draw Interaction, connected to your interaction. By setting its type to Polygon, it only allows polygon
-
Add a map load handler to the
olmsinitialization. Inside, defineVectorlayersparcelandLayer interaction. Provide a blackLayer Strokeand blueFillstyle forparcel. Add each to the map withLayer map.add.Layer Use dark colors for code blocks olms.apply(map, basemapURL).then(function (map) { const parcelLayer = new ol.layer.Vector({ source: new ol.source.Vector({ }), style: new ol.style.Style({ stroke: new ol.style.Stroke({ color: "black" }), fill: new ol.style.Fill({ color: "hsl(200,80%,50%)" }) }) }); const interactionLayer = new ol.layer.Vector({ source: new ol.source.Vector() }); map.addLayer(parcelLayer); map.addLayer(interactionLayer); -
Add the data attribution
Data attribution is the requirement to display the names of data source providers in all applications when accessing ArcGIS content, layers, or services. for the feature layer source.- Go to the LA County Parcels item
An item, also known as a content item, is a resource stored in a portal such as a web map, hosted layer, style, script tool, file, or notebook. . - Scroll down to the Acknowledgments section and copy its value.
- Paste the copied value to the
attributionsproperty.Use dark colors for code blocks olms.apply(map, basemapURL).then(function (map) { const parcelLayer = new ol.layer.Vector({ source: new ol.source.Vector({ // Attribution text retrieved from https://arcgis.com/home/item.html?id=a6fdf2ee0e454393a53ba32b9838b303 attributions: ["| County of Los Angeles Office of the Assessor"] }), style: new ol.style.Style({ stroke: new ol.style.Stroke({ color: "black" }), fill: new ol.style.Fill({ color: "hsl(200,80%,50%)" }) }) }); const interactionLayer = new ol.layer.Vector({ source: new ol.source.Vector() }); map.addLayer(parcelLayer); map.addLayer(interactionLayer);
- Go to the LA County Parcels item
-
Create a
Drawinteraction, linked tointeraction, and with a type ofLayer Polygon. Add it to the map withmap.add.Interaction Use dark colors for code blocks map.addLayer(parcelLayer); map.addLayer(interactionLayer); const drawInteraction = new ol.interaction.Draw({ source: interactionLayer.getSource(), type: "Polygon", stopClick: true // don't fire "click" events (needed later) }); map.addInteraction(drawInteraction); -
In the top right, click Run. You can now click to create multiple polygons.
Execute the query
Use the ArcGIS REST JS query method to find features in the LA County Parcels feature layerEsri feature format to read the features
-
Create a function called
executewith aQuery geometryparameter and then callarcgis.Rest.query Features -
Pass the
geometry. Specify JSON as the return type and specifyreturn. All of the featuresGeometry A feature is a single record, also known as a row, that represents a real-world entity. It typically contains a geometry (point, multipoint, polyline, or polygon) and attributes but it can also contain just attributes. within the geometryA geometry is a geometric shape, such as a point, polyline, or polygon, that contains one or more coordinates and a spatial reference. will be returned.There are many other spatial relationships that you can specify with
spatial. For example, you can useRel esrito only return parcels within the sketched polygon. See the ArcGIS services reference for details.Spatial Rel Contains Use dark colors for code blocks map.addInteraction(drawInteraction); function executeQuery(geometry) { arcgisRest .queryFeatures({ url: "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0", geometry: geometry, geometryType: "esriGeometryPolygon", spatialRel: "esriSpatialRelIntersects", f: "json", returnGeometry: true }) } -
Add a response handler. Inside, use an
Esrifeature format to set the returned parcels as the parcel layer's source.JSON Use dark colors for code blocks function executeQuery(geometry) { arcgisRest .queryFeatures({ url: "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/LA_County_Parcels/FeatureServer/0", geometry: geometry, geometryType: "esriGeometryPolygon", spatialRel: "esriSpatialRelIntersects", f: "json", returnGeometry: true }) .then((response) => { const features = new ol.format.EsriJSON().readFeatures(response); parcelLayer.getSource().addFeatures(features); }); }
Trigger the query
When the user completes a polygon, the drawend event is fired, with an object containing the new polygon as a feature attribute. You can use this feature to call execute.
Use the Esri feature format to convert the query polygon into the ArcGIS geometry format. It is not necessary to reproject the data.
-
Add a handler for the
drawevent. Inside, use anEnd Esrifeature format to convert the feature into an ArcGIS JSON format. Ensure the map's spatial referenceJSON A spatial reference is a set of parameters, typically defined by a WKID, that define the coordinate system and spatial properties for geographic data. Applications use a spatial reference to correctly display the position of geographic data in a map or scene. information is included, by setting thefeatureproperty. CallProjection executewith this feature's geometry.Query Use dark colors for code blocks map.addInteraction(drawInteraction); drawInteraction.on("drawend", (e) => { const feature = new ol.format.EsriJSON().writeFeatureObject(e.feature, { featureProjection: map.getView().getProjection() }); executeQuery(feature.geometry); }); -
At the top right, click Run. When you draw a polygon
A polygon is a type of geometry containing an array of rings and a spatial reference. Each ring contains an array of point coordinates, where the first and last point are the same. , a spatial query will run against the feature layerA feature layer (client-side) is a data layer that can access and display features from a feature service that has the same type of geometry and attribute fields. and display all land parcels within the boundary of the featureA feature is a single record, also known as a row, that represents a real-world entity. It typically contains a geometry (point, multipoint, polyline, or polygon) and attributes but it can also contain just attributes. . Interaction polygons and parcels returned from previous queries remain visible. You will address this next.
Add a pop-up
The parcels returned from the query contain many attributes, such as land value and land use type. You can make the parcels interactive by showing a pop-up when the user clicks on a parcel. You create a Popup to display parcel attributes. It is a type of Overlay so you add it to the map with map.add.
In order for clicking to trigger a pop-up, and not draw another polygon, you need to enable and disable the draw interaction using set. Disable the interaction when the user has drawn a complete polygon. Enable it again when the user clicks somewhere other than a parcel, to reset the map. Clear the parcels and interaction layer at the same time.
-
Create a
Popupand save it to apopupvariable. Add it to the map withmap.add.Overlay Use dark colors for code blocks .then((response) => { const features = new ol.format.EsriJSON().readFeatures(response); parcelLayer.getSource().addFeatures(features); }); } const popup = new Popup(); map.addOverlay(popup); -
Create a map
clickevent handler. Inside, usemap.getto get the clicked parcel, if any. If there is one, useFeatures At Pixel popup.showto display a pop-up containing the parcel's APN, use type, land value and taxation city.Use dark colors for code blocks const popup = new Popup(); map.addOverlay(popup); map.on("click", (event) => { let parcel = map.getFeaturesAtPixel(event.pixel, { layerFilter: (l) => l === parcelLayer })[0]; if (parcel) { // user clicked on a parcel to see more information about it const message = `<b>Parcel ${parcel.get("APN")}</b>` + `<br>Type: ${parcel.get("UseType")} <br>` + `Land value: ${parcel.get("Roll_LandValue")} <br>` + `Tax Rate City: ${parcel.get("TaxRateCity")}`; popup.show(event.coordinate, message); drawInteraction.abortDrawing(); } else { } }); -
If the user did not click a parcel, hide the pop-up with
popup.hide. Clear each layer by callingclearon itsSource. Usesetto enableActive draw.Interaction Use dark colors for code blocks popup.show(event.coordinate, message); drawInteraction.abortDrawing(); } else { // user clicked elsewhere on the map to reset popup.hide(); parcelLayer.getSource().clear(); interactionLayer.getSource().clear(); drawInteraction.setActive(true); -
In the
drawendevent handler, usesetto disableActive draw.Interaction Use dark colors for code blocks drawInteraction.on("drawend", (e) => { const feature = new ol.format.EsriJSON().writeFeatureObject(e.feature, { featureProjection: map.getView().getProjection() }); executeQuery(feature.geometry); drawInteraction.setActive(false);
Run the app
Run the app.
When you click on the map to draw a polygonWhat's next?
Learn how to use additional location services in these tutorials:

Query a feature layer (SQL)
Execute a SQL query to access polygon features from a feature layer.

Get global data
Query demographic information for locations around the world.

Get local data
Query regional facts and spending trends for a study area in the United States.

Add a feature layer as GeoJSON
Display and style GeoJSON features from a feature service.

Style a feature layer
Use data-driven styling to apply symbol colors and styles to feature layers.