views:

246

answers:

2

Having trouble converting an Ilayer to an IPolygon.

I am developing a toolbar for ArcMap and I grab a layer via code from the side table of contents. The Layer is a Polygon, but the code won't convert it to a IPolygon.

Can anyone help me out? This is the code I am using to try and convert it to a IPolygon...

 IPolygon poly = m_document.Maps.get_Item(0).get_Layer(0) as IPolygon;

I can do this:

 ILayer layer = m_document.Maps.get_Item(0).get_Layer(0) as ILayer;

And that works, just not converting it to a IPloygon..

A: 

The ILayer will be made up of multiple polygons. Think of a layer as a sql table and a feature as a row in that table. The IPolygon will refer to the geometry that makes up an individual feature. You may need to cast that ILayer as something like an IFeatureLayer to get access to the right properties/methods to access the individual features within your layer.

smencer
Makes Sense... But how to pull the IPolygon out of the IFeatureClass or Layer? The closest thing I have that I can get is AreaOfInterest and that gets converted to an IEnvelope... Tried creating a new IPolygon Class, but the IEnvelope feature is read only....
Scott
Yeah, you cannot instantiate the interfaces directly.Basically, from the IFeatureLayer, you can access the FeatureClass property. From the FeatureClass, you can call the GetFeatures() method, which returns a cursor that allows you to iterate over all of the features in the FeatureClass. You should be able to access the geometry associated with each feature.An example (in VB) can be found here:http://resources.esri.com/help/9.3/ArcGISDesktop/ArcObjects/esriGeoDatabase/IFeatureClass_GetFeatures.htm
smencer
+2  A: 

If you want to access the geometries contained in a shapefile layer, you have to get the layer's feature class. This is a property of the IFeatureLayer interface, so you'll have to cast your layer (which is an ILayer) first:

IFeatureLayer FLayer = layer as IFeatureLayer;
IFeatureClass FClass = FLayer.FeatureClass;

If you have a feature class, you can get features by index (slow) or by defining a cursor on the feature class (this is fast and the preferred way when you want to handle lots of features. Search for IFeatureCursor; ESRI docs usualy come with good code snippets).

If your feature class contains only one feature, or if you only want one feature, You can use the GetFeature method:

IFeature MyFeature = FClass.GetFeature(0);

Now you're almost there. A feature's geometry is tucked away in its Shape property:

IPolygon MyPoly = MyFeature.Shape as IPolygon;

The extra cast is needed because the Shape property is an IPolygon, which is a more specific IGeometry.

cfern
That was it!!! Thank you soo much!
Scott