How to find the shortest path using RasterDistanceOp


This sample code demonstrates how to find the shortest path using the IDistanceOp::CostPath method

How to use

  1. Run ArcMap and add the source data, distance and direction rasters as the first, second, and third layers in TOC .
  2. Paste the code into VBA.
  3. Make sure the Spatial Analyst Extension is checked.
  4. Add reference to ESRI SpatialAnalyst Object Library.
  5. From the Macros dialog, run FindShortestPath subroutine.
[VBA]
Sub FindShortestPath()
    'Get the focused map from MapDocument
    Dim pMxDoc As IMxDocument
    Set pMxDoc = ThisDocument
    Dim pMap As IMap
    Set pMap = pMxDoc.FocusMap
    
    'Get the input source data from the first layer in ArcMap
    Dim pSourceGeoDataset As IGeodataset
    Dim pLayer As ILayer
    Dim pFeatureLayer As IFeatureLayer
    Dim pRasLayer As IRasterLayer
    
    Set pLayer = pMap.Layer(0)
    If TypeOf pLayer Is IFeatureLayer Then
        Set pFeatureLayer = pLayer
        Set pSourceGeoDataset = pFeatureLayer.FeatureClass
    ElseIf TypeOf pLayer Is IRasterLayer Then
        Set pRasLayer = pLayer
        Set pSourceGeoDataset = pRasLayer.Raster
    Else
        Exit Sub
    End If
    
    'Get the distance raster from the second layer
    Dim pDistanceRaster As IRaster
    
    Set pLayer = pMap.Layer(1)
    If Not TypeOf pLayer Is IRasterLayer Then
        Exit Sub
    End If
    Set pRasLayer = pLayer
    Set pDistanceRaster = pRasLayer.Raster
    
    'Get the direction (backlink) raster from the third layer
    Dim pDirectionRaster As IRaster
    
    Set pLayer = pMap.Layer(2)
    If Not TypeOf pLayer Is IRasterLayer Then
        Exit Sub
    End If
    Set pRasLayer = pLayer
    Set pDirectionRaster = pRasLayer.Raster
    
    'Create a RasterDistanceOp operator
    Dim pDistanceOp As IDistanceOp
    Set pDistanceOp = New RasterDistanceOp
    
    'Set output workspace
    Dim pEnv As IRasterAnalysisEnvironment
    Set pEnv = pDistanceOp
    Dim pWS As IWorkspace
    Dim pWSF As IWorkspaceFactory
    Set pWSF = New RasterWorkspaceFactory
    Set pWS = pWSF.OpenFromFile("c:\temp", 0)
    Set pEnv.OutWorkspace = pWS
    
    'Find the shortest path
    Dim pOutRaster As IRaster
    Set pOutRaster = pDistanceOp.CostPath(pSourceGeoDataset, pDistanceRaster, pDirectionRaster, esriGeoAnalysisPathForEachCell)
    
    'Add output into ArcMap as a raster layer
    Dim pOutRasLayer As IRasterLayer
    Set pOutRasLayer = New RasterLayer
    pOutRasLayer.CreateFromRaster pOutRaster
    pMap.AddLayer pOutRasLayer
End Sub