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:
For a discussion of creating objects on ArcGIS Server, see the quickstart, Getting started with ArcGIS Server.
Click on the link below to learn how to:
An ArcGIS Engine-based application must initialize certain environment variables and check out a license before it can execute.
EngineInitializer.initializeEngine(); AoInitialize aoInit = new AoInitialize(); aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeEngine);
EngineInitializer. initializeVisualBeans(); AoInitialize aoInit = new AoInitialize(); aoInit.initialize(esriLicenseProductCode.esriLicenseProductCodeEngine);
aoInit.initialize(esriLicenseExtensionCode.esriLicenseExtensionCodeSpatialAnalyst); aoInit.initialize(esriLicenseExtensionCode.esriLicenseExtensionCode3DAnalyst);
This code shows how to connect to an ArcGIS server, impersonate a user, and create a blank server context.
new ServerInitializer().initializeServer(domain, user, password);
ServerConnection connection = new ServerConnection();
connection.connect(host);
IServerObjectManager som = connection.getServerObjectManager();
sc = som.createServerContext("", "");
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()));
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,"");
}
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");
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));
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.
WorkspaceFactory object within the Server's context.
IWorkspaceFactory pWorkspaceFactory = new IWorkspaceFactoryProxy(context.createObject("esriDataSourcesGDB.SdeWorkspaceFactory"));
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");
IWorkspace ws = pWorkspaceFactory.open(propSet,0);
IEnumDataset dsenum = ws.getDatasets(esriDatasetType.esriDTFeatureDataset);
IDataset ds = dsenum.next();
while(ds != null){
System.out.println(ds.getName());
ds = dsenum.next();
}
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());
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);
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));
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"));
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));
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);
This example assumes you have opened a feature class, such as from a shapefile or a personal geodatabase.
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();
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();
}
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");
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();
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);
The map used in this example must have selected features.
MapSelection mapSelection = new MapSelection(map.getFeatureSelection());
mapSelection.reset();
IFeature feature = mapSelection.next();
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));
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);
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.
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);
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);