I'm relatively new to programming and ArcObjects. I'm trying to simply calculate the length of a line (test.shp) using ArcObjects and Java. I've tried the code below with no luck. This is simple in ArcMap because one just needs to use 'calculate geometry' on the field within the attribute table. But I need code to do this.
Any suggestions would be greatly appreciated!
FeatureClass fc1 = null;
ShapefileWorkspaceFactory shapefileWorkspaceFactory = new ShapefileWorkspaceFactory(); Workspace shapefileWorkspace = new Workspace(shapefileWorkspaceFactory.openFromFile("c:/PFRAS/TEMP", 0));
fc1 = new FeatureClass(shapefileWorkspace.openFeatureClass("test.shp"));
Field fe = new Field();
fe.setName("Dist");
fe.setType(esriFieldType.esriFieldTypeDouble);
fe.setScale(2);
fe.setPrecision(16);
fc1.addField(fe);
IFeature feature = fc1.getFeature(0);
Line line = new Line();
//Assume that the underlying feature is a Line.
IGeometry geom = feature.getShape();
if (geom instanceof Line)
line = (Line)geom;
double length = line.getLength();
int fieldIndex = fc1.findField("Dist");
FeatureCursor fCursor = new FeatureCursor(fc1.IFeatureClass_update(null, false));
Feature feature2 = (Feature) fCursor.nextFeature();
while (feature2 != null)
{
feature2.setValue(fieldIndex, length);
fCursor.updateFeature(feature2);
feature2 = (Feature) fCursor.nextFeature();
}
fCursor.flush();
Cleaner.release(fCursor);
1 Answer 1
I did solve this problem after using the ICurve .getLength() method as suggested by artwork21 user. Here is the code.
FeatureClass fc1 = null;
ShapefileWorkspaceFactory shapefileWorkspaceFactory = new ShapefileWorkspaceFactory();
Workspace shapefileWorkspace = new Workspace(shapefileWorkspaceFactory.openFromFile("c:/TEMP", 0));
fc1 = new FeatureClass(shapefileWorkspace.openFeatureClass("test.shp"));
//Create cumulative distance field using Field class
Field fe = new Field();
fe.setName("Cum_Dist");
fe.setType(esriFieldType.esriFieldTypeDouble);
fe.setScale(2);
fe.setPrecision(16);
fc1.addField(fe);
//Create field index
int fieldIndex = fc1.findField("Cum_Dist");
//Get reference to the line feature and calculate length using ICurve interface
IFeature feature = fc1.getFeature(0);
ICurve curve = (ICurve)feature.getShape();
double length = curve.getLength();
//Use a FeatureCursor to addign the length value to the field
FeatureCursor fCursor = new FeatureCursor(fc1.IFeatureClass_update(null, false));
Feature feature2 = (Feature) fCursor.nextFeature();
while (feature2 != null)
{
feature2.setValue(fieldIndex, length);
fCursor.updateFeature(feature2);
feature2 = (Feature) fCursor.nextFeature();
}
fCursor.flush();
Cleaner.release(fCursor);
IFeature feature = fc1.getFeature(0); Line line = new Line(); //Assume that the underlying feature is a Line. IGeometry geom = feature.getShape(); if (geom instanceof Line) line = (Line)geom; double length = line.getLength();