How to execute map algebra using RasterMapAlgebraOp


This sample code demonstrates how to execute Map Algebra expression using IMapAlgebraOp methods

How to use

  1. Start ArcMap and add an elevation raster dataset.
  2. Paste the code into VBA.
  3. Make sure the Spatial Analyst extension is checked.
  4. Add reference to ESRI SpatialAnalyst Object Library.
  5. Run the sub from the Macros dialog.
[VBA]
Sub MapAlgebra()
    'Get the focused map from MapDocument
    Dim pMxDoc As IMxDocument
    Set pMxDoc = ThisDocument
    Dim pMap As IMap
    Set pMap = pMxDoc.FocusMap
    
    'Get the input raster from the first layer in ArcMap
    Dim pLayer As ILayer
    Set pLayer = pMap.Layer(0)
    If Not TypeOf pLayer Is IRasterLayer Then
        Exit Sub
    End If
    
    Dim pRasLayer As IRasterLayer
    Set pRasLayer = pLayer
    Dim pInRaster As IRaster
    Set pInRaster = pRasLayer.Raster
    
    'Create a RasterMapAlgebraOp operator
    Dim pMapAlgebraOp As IMapAlgebraOp
    Set pMapAlgebraOp = New RasterMapAlgebraOp
    
    'Set output workspace
    Dim pEnv As IRasterAnalysisEnvironment
    Set pEnv = pMapAlgebraOp
    Dim pWS As IWorkspace
    Dim pWSF As IWorkspaceFactory
    Set pWSF = New RasterWorkspaceFactory
    Set pWS = pWSF.OpenFromFile("c:\temp", 0)
    Set pEnv.OutWorkspace = pWS
    
    'Bind a raster
    pMapAlgebraOp.BindRaster pInRaster, "R1"
    
    'Execute the Map Algebra expression to calculate slope of the input raster
    Dim pOutRaster As IRaster
    Set pOutRaster = pMapAlgebraOp.Execute("Slope([R1])")
    
    'Add output into ArcMap as a raster layer
    Dim pOutRasLayer As IRasterLayer
    Set pOutRasLayer = New RasterLayer
    pOutRasLayer.CreateFromRaster pOutRaster
    pMap.AddLayer pOutRasLayer
End Sub