[GIS] How to use the IRelationalOperator interface to check if a point feature within a polygon feature

arcobjectsc

I use the following code to check if a point feature is within a polygon feature

pFeaBlock is a polygon feature and Fea is a point feature

int blockID = -1;
IFeatureCursor pBlockCursor = this._blockLayer.Search(null, false);
IFeature pFeaBlock = pBlockCursor.NextFeature();
while (pFeaBlock != null)
{
    if (!pFea.Shape.IsEmpty)
    {
      IPolygon pPolygon = (IPolygon)pFea.Shape;
      IRelationalOperator pRelOperator = (IRelationalOperator)pPolygon;
      if (pRelOperator.Within(pFeaBlock.Shape) == true)
      {
          blockID = (int)pFeaBlock.get_Value(2);
      }
     }

     pFeaBlock = pBlockCursor.NextFeature();
 }

but I always get he COMException on

if (pRelOperator.Within(pFeaBlock.Shape) == true)

Is anyone familiar this interface?
Thanks in advance

Best Answer

First, check if the relational Operator is Null. But your problem is with the geometries: You need to be sure that the relational operatior can be used. For that both spatial references need to be the same. You can useSpatialReference.FactoryCodefor check it.

while ((IFeature pFeaBlock = pBlockCursor.NextFeature()) != null)
{
  if (!pFea.Shape.IsEmpty)
  {
    IPolygon pPolygon = (IPolygon)pFea.Shape;
    if (pPolygon.SpatialReference.FactoryCode == pFeaBlock.Shape.SpatialReference.FactoryCode)
    {        
      IRelationalOperator pRelOperator = (IRelationalOperator)pPolygon;
      if (pRelOperator.Within(pFeaBlock.Shape) == true)
      {
        blockID = (int)pFeaBlock.get_Value(2);
      }
    }
  }   
}
Related Question