How to work with a spatial query


This sample builds a spatial query filter, gets a feature cursor based on the filter and then loops over all the features, totaling the number of points, lines, and areas, and reports these to the user.
The code samples in this section show the fundamentals of programming with ArcObjects. A careful reading of them gives you all the important concepts you need for developing with ArcObjects, as well as an introduction to the most important ArcObjects components.
The code can be typed or copied into the VBA environment in ArcMap or ArcCatalog, after which you can follow through with the VBA debugger.

How to use

  1. Add the code to the Click event of a UIButtonControl in ArcMap.
[VBA]
Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument

Dim pEnv As IEnvelope
Dim pRubber As IRubberBand
Set pRubber = New RubberEnvelope

Dim pActiveView As IActiveView
Set pActiveView = pMxDoc.FocusMap
Set pEnv = pRubber.TrackNew(pActiveView.ScreenDisplay, Nothing)

Dim pSpatialFilter As ISpatialFilter
Set pSpatialFilter = New SpatialFilter
Set pSpatialFilter.Geometry = pEnv
pSpatialFilter.SpatialRel = esriSpatialRelIntersects

Dim lPoints As Long, lPolygons As Long, lPolylines As Long
Dim pLayer As IFeatureLayer
Dim pFeatureCursor As IFeatureCursor
Dim pFeature As IFeature
Dim i As Long
For i = 0 To pMxDoc.FocusMap.LayerCount - 1
    If (TypeOf pMxDoc.FocusMap.Layer(i) Is IGeoFeatureLayer) Then
        Set pLayer = pMxDoc.FocusMap.Layer(i)
        pSpatialFilter.GeometryField = pLayer.FeatureClass.ShapeFieldName
        Set pFeatureCursor = pLayer.Search(pSpatialFilter, True)
        Set pFeature = pFeatureCursor.NextFeature
        Do Until (pFeature Is Nothing)
            Select Case pFeature.Shape.GeometryType
                Case esriGeometryPoint
                    lPoints = lPoints + 1
                Case esriGeometryPolyline
                    lPolylines = lPolylines + 1
                Case esriGeometryPolygon
                    lPolygons = lPolygons + 1
            End Select
            Set pFeature = pFeatureCursor.NextFeature
        Loop
    End If
Next i
MsgBox "Features Found:" & vbCrLf & lPoints & " Points " & vbCrLf & lPolylines & " Polylines " & vbCrLf & lPolygons & " Polygons "