How to execute map algebra using RasterModel


This sample code demonstrates how to execute complex multilines Map Algebra expression using IRasterModel methods

How to use

  1. Start ArcMap and add a raster dataset.
  2. Paste the code into VBA.
  3. Make sure the Spatial Analyst extension is checked.
  4. Add reference to ESRI GeoAnalyst Object Library.
  5. Run the sub from the Macros dialog.
[VBA]
Sub RasterModel()
    'Get the focused map from MapDocument
    Dim pMxDoc As IMxDocument
    Dim pMap As IMap
    Set pMxDoc = ThisDocument
    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 RasterModel object
    Dim pRasModel As IRasterModel
    Set pRasModel = New RasterModel
    
    'Set output workspace in the analysis environment
    Dim pEnv As IRasterAnalysisEnvironment
    Set pEnv = pRasModel
    
    Dim pWS As IWorkspace
    Dim pWSF As IWorkspaceFactory
    Set pWSF = New RasterWorkspaceFactory
    Set pWS = pWSF.OpenFromFile("c:\temp", 0)
    Set pEnv.OutWorkspace = pWS
    
    'Bind the input raster
    pRasModel.BindRaster pInRaster, "input1"
    
    'Specify map algebra expression, use vbLf to create seperate lines
    pRasModel.Script = "[out1] = [input1] + 50" + vbLf + _
                       "[out2] = Slice([out1], Eqinterval, 5)" + vbLf + _
                       "[out3] = [out1] + 100 * [out2]"
    
    'Execute map algebra expression(s)
    pRasModel.Execute
    
    'Get output rasters
    Dim pOutRaster1 As IRaster
    Set pOutRaster1 = pRasModel.BoundRaster("out1")
    
    Dim pOutRaster2 As IRaster
    Set pOutRaster2 = pRasModel.BoundRaster("out2")
    
    Dim pOutRaster3 As IRaster
    Set pOutRaster3 = pRasModel.BoundRaster("out3")
    
    'Unbind input raster
    pRasModel.UnbindSymbol "input1"
    
    'Add outputs into ArcMap as raster layers
    Dim pOutRasLayer1 As IRasterLayer
    Set pOutRasLayer1 = New RasterLayer
    
    pOutRasLayer1.CreateFromRaster pOutRaster1
    pMap.AddLayer pOutRasLayer1
    
    Dim pOutRasLayer2 As IRasterLayer
    Set pOutRasLayer2 = New RasterLayer
    
    pOutRasLayer2.CreateFromRaster pOutRaster2
    pMap.AddLayer pOutRasLayer2
    
    Dim pOutRasLayer3 As IRasterLayer
    Set pOutRasLayer3 = New RasterLayer
    
    pOutRasLayer3.CreateFromRaster pOutRaster3
    pMap.AddLayer pOutRasLayer3
End Sub