Search code examples
c#arcgis

Is this an accurate way to decide if one geometry is contained in another?


I have C# ArcGis application, and inside I use graphic layers. I want to decide what graphics of the layer are contained inside a polygon. Is this the correct/accurate way to do it?

var identifiedGraphics = new List<Graphic>();
var polygonExtent = (drawnGeometry as Polygon).Extent;

if (layer.Graphics != null)
{
   foreach (var graphic in layer.Graphics)
   {
      if (polygonExtent.Intersects(graphic.Geometry.Extent))
      {
          identifiedGraphics.Add(graphic);
      }
   }
}

Edit - This isn't accurate' it gets me graphic that are close to the polygon. Any ideas? I'm using ESRI.ArcGIS.Client


Solution

  • var graphicsToReturn = new List<Graphic>();
    var geometryService = new GeometryService();
    geometryService.InitializeWithLocalService();
    
    foreach (var currentGraphic in layer.Graphics)
    {
        var intersectSection = geometryService.Intersect(new List<Graphic> { currentGraphic }, polygonGeometry);
    
        if (intersectSection != null)
        {
            foreach (var intersectionGraphic in intersectSection)
            {
                  if (intersectionGraphic != null )
                  {
                      var polygon = intersectionGraphic.Geometry as Polygon;
                      var point = intersectionGraphic.Geometry as MapPoint;
                      var line = intersectionGraphic.Geometry as Polyline;
    
                      if (polygon != null && polygon.Rings.Count > 0)
                      {
                         graphicsToReturn.Add(currentGraphic);
                      }
                      else if (point != null && !double.IsNaN(point.X) && !double.IsNaN(point.Y))
                      {                                     
                         graphicsToReturn.Add(currentGraphic);
                      }
                      else if (line != null && line.Paths.Count > 0)
                      {
                         graphicsToReturn.Add(currentGraphic);
                      }
                   }
              }
          }
     }
    

    Explanation: The GeometryService is a service that has all sorts of methods but needs a URL to the given service we are working on. If there is not service it has to be initialized with "InitializeWithLocalService" which creates a local service. The Intersect method DOES NOT return the intersected graphics, what it does is returns a geometry that represents the intersect section between the 2 parameters it receives. So to check if something intersects, you can call this method and check if the return parameter isn't basically an "empty" geometry like in the above code. (The type of the geometry that is returned is the same as the first parameter sent to the Intersect method in this case.)