Programming with ArcObjects  

Working with ArcObjects-Code Snippets


This document includes ArcObjects code examples for some of the more common tasks you might need your custom application to perform.

Some notes for using these code examples:

 

Click on the link below to learn how to:

  1. Initialize an engine application
  2. Connect to ArcGIS Server
  3. Create objects on the server
  4. Open a map
  5. Open a Shapefile
  6. Open a DBF file
  7. Open a SDE connection with the Server API
  8. Open a CAD file
  9. Open a TIN coverage
  10. Open a raster
  11. Open a personal geodatabase
  12. Get a layer from a Map
  13. Create a layer from a FeatureClass
  14. Work with the attributes of a FeatureClass
  15. Create a query filter
  16. Select features from a layer based upon attributes
  17. Perform a spatial query on a map
  18. Buffer off of selected features
  19. Add items to the graphics container of a map
  20. Project data from one coordinate system to another

 

Initialize an ArcGIS Engine application

An ArcGIS Engine-based application must initialize certain environment variables and check out a license before it can execute.

  1. First, initialize environment variables and acquire an Engine license.
  2. EngineInitializer.initializeEngine();
    AoInitialize aoInit = new AoInitialize();
    aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeEngine);

    If you are working with the ArcGIS controls (visual JavaBeans found in the com.esri.arcgis.beans.xxxx packages), then the initialization code looks like this:
    EngineInitializer. initializeVisualBeans();
    AoInitialize aoInit = new AoInitialize();
    aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeEngine); 
  3. If your application requires the use of an extension product, such as Spatial Analyst or 3D Analyst, then you need to check these licenses as well. This code cannot precede the initial license checkout.
  4. aoInit.initialize(esriLicenseExtensionCode.esriLicenseExtensionCodeSpatialAnalyst);
    aoInit.initialize(esriLicenseExtensionCode.esriLicenseExtensionCode3DAnalyst); 

 

Connect to ArcGIS Server

This code shows how to connect to an ArcGIS server, impersonate a user, and create a blank server context.

  1. Initialize ArcObjects for Server usage, where domain is the authenticating domain, user is a user in agsadmin or agsuser group, and password is the password for the user
  2. new ServerInitializer().initializeServer(domain, user, password);
  3. Connect to the host machine where the ArcGIS Server Object Manager is running, get the SOM, and create an empty context
  4. ServerConnection connection = new ServerConnection();
    connection.connect(host);
    IServerObjectManager som = connection.getServerObjectManager();
    sc = som.createServerContext("", "");
    

 

Create objects on the Server

Since server objects are created remotely they have a different syntax. In an ArcGIS Engine-based application you create a point with this code:

Point point = new Point();


While with ArcGIS Server you create the point like this:

Point point = new Point(context.createObject(Point.getClsid()));


Creating a proxy is similar:

IPoint point = new IPointProxy(context.createObject(Point.getClsid()));

 

Open a Map document (.mxd)

When you programmatically open a map document, you can access all the information defined within a map file (.mxd). In this case, mapLocation is the fully qualified path to the map document, including the file extension, .mxd.

MapDocument mapDocument = new MapDocument();

if (mapDocument.isPresent(mapLocation)){
mapDocument.open(mapLocation,""); }

 

Open a shapefile

In this code, the file extension, .shp, is not used when specifying the name of the shapefile to be opened.

ShapefileWorkspaceFactory wsf = new ShapefileWorkspaceFactory();
Workspace work = new Workspace(wsf.openFromFile(location,0));
IFeatureClass featureClass = work.openFeatureClass("NameOfYourShapefile");

 

Open a DBase (dbf) file

In this case, pathToFile is the path to the folder holding the dbf file. Additionally, the file extension, .dbf, must be included when specifying the name of the DBase file.

ShapefileWorkspaceFactory shapefileWorkspaceFactory = new ShapefileWorkspaceFactory();
Workspace workspace = new Workspace(shapefileWorkspaceFactory.openFromFile(pathToFile,0)); Table table = new Table(workspace.openTable(fileName));

 

Open a SDE connection with Server

This example uses ArcObjects to connect directly to ArcSDE and get data sets rather than using the MapServer object to get the ArcSDE layers in a Map.

  1. Create a WorkspaceFactory object within the Server's context.
    IWorkspaceFactory pWorkspaceFactory = new IWorkspaceFactoryProxy(context.createObject("esriDataSourcesGDB.SdeWorkspaceFactory")); 
  2. Create an instance of a PropertySet for an Oracle ArcSDE connection. The PropertySet acts as an array of keyed values that ArcSDE will use to collect the connection values from:

    PropertySet propSet = new PropertySet(context.createObject("esrisystem.PropertySet"));
    propSet.setProperty("SERVER", "pine");
    propSet.setProperty("INSTANCE", "9091");
    propSet.setProperty("DATABASE", "");
    propSet.setProperty("USER", "map");
    propSet.setProperty("PASSWORD", "map");
    propSet.setProperty("VERSION", "SDE.DEFAULT");
       
  3. Open the ArcSDE workspace and get a handle to it through the WorkspaceFactory, passing in the PropertySet:

    IWorkspace ws = pWorkspaceFactory.open(propSet,0);
  4. You now have a connection to the database through a Workspace object (“ws”). In this example, the feature datasets are listed out:

    IEnumDataset dsenum = ws.getDatasets(esriDatasetType.esriDTFeatureDataset);
    IDataset ds = dsenum.next();
    while(ds != null){
    	System.out.println(ds.getName());
    	ds = dsenum.next();
    }

 

Open a CAD file

In this example, the method for opening a Workspace is different than in other examples. In this case, you work with a WorkspaceName. All of the workspace factories in the com.esri.arcgis.datasourcesfile package can be referenced as a factory. The proper suffix must be included in fileName.

WorkspaceName workspaceName = new WorkspaceName();
workspaceName.setWorkspaceFactoryProgID("esriDataSourcesFile.CadWorkspaceFactory"); workspaceName.setPathName(filePath); CadDrawingName cadDrawingName = new CadDrawingName(); cadDrawingName.setName(fileName); cadDrawingName.setWorkspaceNameByRef(workspaceName); CadLayer cadLayer = new CadLayer(cadDrawingName.open());

 

Open a TIN file

This example opens a TIN (Triangulated Irregular Network) from a file. TIN coverages, like all coverages, are actually a folder and not a file name.

Tin tin = new Tin();
tin.init(tinPathAndTinName);

 

Open a Raster DataSet

Depending on the type of raster you are opening, the suffix may or may not be needed. For a GRID raster, specify the pathname including the GRID directory. For a TIFF or .img file, specify the suffix in the fileName.

RasterWorkspaceFactory rasterWorkspaceFactory = new RasterWorkspaceFactory();
RasterWorkspace rasterWorkspace = new RasterWorkspace(rasterWorkspaceFactory.openFromFile(directoryName,0));
rasterDataset = new RasterDataset(rasterWorkspace.openRasterDataset(fileName));

 

Open a personal geodatabase

You can only open a personal geodatabase on a MS Windows computer. The file name should include the .mdb suffix for the file.

AccessWorkspaceFactory wsf = new AccessWorkspaceFactory();
Workspace wspace = new Workspace(wsf.openFromFile(fileName,0));
FeatureClass featureClass = new FeatureClass(wspace.openFeatureClass("AFeatureClass"));

 

Get a layer from a map

Since a map document can contain multiple maps, the getMap method requires an int for choosing a map. The same concept applies to layers within a map.

Map map = new Map(mapDocument.getMap(0));
FeatureLayer layer0 = new FeatureLayer(map.getLayer(0));

 

Create a layer from a feature class

This example assumes you have opened a feature class, such as from a shapefile or a personal geodatabase. After setting the FeatureClass for a layer you can then add the layer to a map.

FeatureLayer featureLayer = new FeatureLayer();
featureLayer.setFeatureClassByRef(yourFeatureClass);
map.addLayer(featureLayer);

 

Work with the attributes of a feature class

This example assumes you have opened a feature class, such as from a shapefile or a personal geodatabase.

  1. Get the feature cursor from the feature class and loop through all the field names

    IFeatureCursor featureCursor = featureClass.search(null, true);
    IFields fields = featureCursor.getFields();
    int fieldCount = fields.getFieldCount();
    for (int i = 0; i < fieldCount; i++) { IField fieldI = fields.getField(i); String fieldName = fieldI.getName(); System.out.print(fieldName + "\t");
    } System.out.println();
  2. Use the feature cursor to iterate over all elements in the feature class, printing the values of the fields. All field types are shown here. Simple values are printed as Strings. Complex elements are shown as the type name.

    IFeature feature = featureCursor.nextFeature();
    while (feature != null) {
    StringBuffer row = new StringBuffer();
    for (int i = 0; i < fieldCount; i++) {
    int fieldType = feature.getFields().getField(i).getType();
    switch (fieldType) {
    case esriFieldType.esriFieldTypeDate:
    case esriFieldType.esriFieldTypeDouble:
    case esriFieldType.esriFieldTypeGlobalID:
    case esriFieldType.esriFieldTypeGUID:
    case esriFieldType.esriFieldTypeInteger:
    case esriFieldType.esriFieldTypeOID:
    case esriFieldType.esriFieldTypeSingle:
    case esriFieldType.esriFieldTypeSmallInteger:
    case esriFieldType.esriFieldTypeString:
    row.append(feature.getValue(i) + "\t");
    break;
    case esriFieldType.esriFieldTypeBlob:
    row.append("(blob)" + "\t");
    break;
    case esriFieldType.esriFieldTypeGeometry:
    row.append("(geometry)" + "\t");
    break;
    case esriFieldType.esriFieldTypeRaster:
    row.append("(raster)" + "\t");
    break;
    }
    }
    if (row.length() > 0) {
    System.out.println(row);
    }
    feature = featureCursor.nextFeature();
    }

 

Create a query filter

Query filters allow you to use attribute data to create a subset of your original data. They are used for many different tasks in ArcObjects, such as selecting features in a layer or creating a subset of the features and performing an operation on those features alone. It is important to note that a spatial filter implements IQueryFilter so you can use a query filter in a spatial query as well. When creating a query based upon a string attribute be sure to enclose your string condition in single quotes (e.g. "name='ESRI'")

QueryFilter queryFilter = new QueryFilter();
queryFilter.setWhereClause("Attribute=value"); 

Select features from a layer based upon attributes

Once you have a query filter you can use it to select features in a layer. The second parameter of the selectFeatures method allows you to determine what type of selection to perform, such as create a new selection set, append the selection to the current selection set, and several others.

layer.selectFeatures(queryfilter,esriSelectionResultEnum.esriSelectionResultNew,false);
int numberOfSelectedFeatures = map.getSelectionCount();

 

Perform a spatial query on a map

A spatial filter, which also implements IQueryFilter, searches a feature class for all the features which satisfy the spatial relation with an IGeometry. There are many objects which implement IGeometry, such as Point, MultiPoint, Line, and so on. The list of spatial relations can be found in esriSpatialRelEnum.

SpatialFilter spatialFilter = new SpatialFilter(); 
spatialFilter.setGeometryByRef(searchGeometry);
String shapeFieldString = featureClass.getShapeFieldName();
spatialFilter.setGeometryField(shapeFieldString);
spatialFilter.setSpatialRel(spatialRelation);

if ((whereClause == null )){ spatialFilter.setWhereClause("");
} else {
spatialFilter.setWhereClause(whereClause);
}
featureCursor = featureClass.search(spatialFilter,false);

 

Buffer off of selected features

The map used in this example must have selected features.

  1. Get the selected feature from the map.

    MapSelection mapSelection = new MapSelection(map.getFeatureSelection());
    mapSelection.reset();
    IFeature feature = mapSelection.next();
  2. While all the higher order geometries, such as Point, MultiPoint, Line, and Polygon implement ITopologicalOperator, this sample only uses the interface object. In this way we can perform this operation without worrying about the feature returned by the getShape method. The buffer method returns an IGeometry (which is always a polygon). This geometry can then be used in any method requiring an IGeometry.

    ITopologicalOperator topologicalOperator = new ITopologicalOperatorProxy(feature.getShape());
    Polygon bufferGeometry = new Polygon(topologicalOperator.buffer(bufferDistance));

 

Add items to the graphics container of a map

Graphics layer are generally used to display items on a map. While it is quicker to draw items within a graphics container, this results in reduced functionality. The items on a graphics layer are elements and not features. There are many different objects that implement IElement, ranging from GifPictureElement to Text3DElement. Placing graphic elements on a globe is not supported at 9.1 but will be supported with 9.2. This example will illustrate how to take a feature and use it to create an element.

Point point = new Point();
point.setX(-100.00);
point.setY(40);
MarkerElement markerElement = new MarkerElement();
markerElement.setGeometry(point);
map.addElement(markerElement,0);

 

Project data from one coordinate system to another

Spatial data is collected using a spatial reference system, either geographic coordinates (Degree, Minutes, Seconds) or projected coordinates (UTM, for example). In addition there are different spherical models of the earth called datums. Taking data from one spatial reference system to another is called projection. There are numerous spatial reference systems available in ArcObjects. This example takes data from a geographic coordinate system with a datum of NAD1927 to UTM zone 13 North with a datum of NAD 1983.

  1. Make a spatial reference environment which implements a spatial reference factory, create the spatial reference and apply it to an object implementing IGeometry. In this case, a Point is projected.

    Point point = new Point();
    point.setX(-100.00);
    point.setY(40);
    SpatialReferenceEnvironment sRefEnv = new SpatialReferenceEnvironment();
    ISpatialReference incomingCoordSystem = sRefEnv.createGeographicCoordinateSystem(esriSRGeoCSType.esriSRGeoCS_NAD1927);
    point.setSpatialReferenceByRef(incomingCoordSystem);

  2. Create the spatial reference for the projected coordinate system. Since the datums are also changing, a datum conversion must be specified. Finally, the point is projected.

    ISpatialReference outgoingCoordSystem = sRefEnv.createProjectedCoordinateSystem(esriSRProjCSType.esriSRProjCS_NAD1983UTM_13N);
    NADCONTransformation datumConversion = new NADCONTransformation(sRefEnv.createGeoTransformation(esriSRGeoTransformation2Type.esriSRGeoTransformation_NAD_1927_TO_NAD_1983_NADCON)); point.projectEx(outgoingCoordSystem, esriTransformDirection.esriTransformForward, datumConversion, false,0,0);