private void SetPINValue() { //The Theory. //Select polygons that intersect the sketch. //Construct one polyline from the boundaries and intersect with sketch. //Sort resulting intersection locations (multipoint) by distance of the intersect // from the start of the sketch and create new ordered multipoint. //Loop through new ordered multipoint, select underlying parcel and calc pin. IFeatureLayer featLayer = m_editLayers.CurrentLayer; m_curve = m_edSketch.Geometry as IPolyline; //Search parcel polys by graphic to get feature cursor ISpatialFilter spatialFilter = new SpatialFilter(); spatialFilter.Geometry = m_curve; spatialFilter.GeometryField = m_editLayers.CurrentLayer.FeatureClass.ShapeFieldName; spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelCrosses; IFeatureCursor featCursor = featLayer.Search(spatialFilter,true); IFeature feature = featCursor.NextFeature(); //If we have no intersects then exit if (feature == null) return; //Make a GeomBag of the polygons boundaries (polylines) IGeometryCollection geomBag = new GeometryBagClass(); object missing = Type.Missing; while (feature != null) { ITopologicalOperator poly = feature.Shape as ITopologicalOperator; geomBag.AddGeometry(poly.Boundary,ref missing,ref missing); feature = featCursor.NextFeature(); } //Make one polyline from the boundaries IPolyline polyLineU = new PolylineClass(); ITopologicalOperator topoOp = polyLineU as ITopologicalOperator; topoOp.ConstructUnion(geomBag as IEnumGeometry); //Get the intersections of the boundaries and the curve IPointCollection pointCol = topoOp.Intersect(m_curve, esriGeometryDimension.esriGeometry0Dimension) as IPointCollection; //The point collection is not ordered by distance along the curve so //need to create a new collection with this info int[] pointOrder = new int[pointCol.PointCount]; double dac = 0, dfc = 0; bool bRS = false; for (int i = 0; i < pointCol.PointCount; i++) { IPoint queryPoint = new PointClass(); pointCol.QueryPoint(i, queryPoint); m_curve.QueryPointAndDistance(esriSegmentExtension.esriNoExtension, queryPoint, false, null,ref dac,ref dfc,ref bRS); pointOrder[i] = (int)dac; } //use built in bubble sort System.Array.Sort(pointOrder); //Loop through the sorted array and calc midpoint between parcel boundaries IPointCollection midPoints = new MultipointClass(); for (int i = 0; i < pointOrder.Length -1; i++) { //Get the midpoint distance double midPointDist = (pointOrder[i] + pointOrder[i + 1]) / 2; //create a point at the distance and store in point collection IPoint queryPoint = new PointClass(); m_curve.QueryPoint(esriSegmentExtension.esriNoExtension, midPointDist, false, queryPoint); midPoints.AddPoint(queryPoint,ref missing,ref missing); } //If ends of sketch are included then add them as points if (chkEnds.Checked) { object before = 0 as object; midPoints.AddPoint(m_curve.FromPoint, ref before, ref missing); midPoints.AddPoint(m_curve.ToPoint, ref missing, ref missing); } m_editor.StartOperation(); //Loop through calculated midpoints, select polygon and calc pin for (int i = 0; i < midPoints.PointCount; i++) { IPoint midPoint = midPoints.get_Point(i); spatialFilter = new SpatialFilter(); spatialFilter.Geometry = midPoint; spatialFilter.GeometryField = m_editLayers.CurrentLayer.FeatureClass.ShapeFieldName; spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelWithin; featCursor = featLayer.Search(spatialFilter, false); while ((feature = featCursor.NextFeature()) != null) { feature.set_Value(feature.Fields.FindField(cmbPINField.Text), m_lotNum); feature.Store(); m_lotNum += int.Parse(txtlotinc.Text); } } m_editor.StopOperation("ViperPIN"); txtlot.Text = m_lotNum.ToString(); }
//Function: Judging whether regional breaks have occurred public bool isRegionalBreak(IFeatureClass featureClass, int elementId) { IGeometry geometryBag = new GeometryBagClass(); IQueryFilter queryFilter = new QueryFilterClass(); queryFilter.WhereClause = "id = " + elementId; IFeatureCursor featureCursor = featureClass.Search(queryFilter, false); IGeometryCollection geometryCollection = geometryBag as IGeometryCollection; IFeature currentFeature = featureCursor.NextFeature(); while (currentFeature != null) { object missing = Type.Missing; geometryCollection.AddGeometry(currentFeature.Shape, ref missing, ref missing); currentFeature = featureCursor.NextFeature(); } ITopologicalOperator unionedPolygon = new PolygonClass(); unionedPolygon.ConstructUnion(geometryBag as IEnumGeometry); IGeometryCollection geoCol = unionedPolygon as IGeometryCollection; if (geoCol.GeometryCount > 1) { return(true); } else { return(false); } }
public static IGeometryCollection ConstructMultiPatchOutline(IGeometry multiPatchGeometry) { IGeometryCollection outlineGeometryCollection = new GeometryBagClass(); IGeometryCollection multiPatchGeometryCollection = multiPatchGeometry as IGeometryCollection; for (int i = 0; i < multiPatchGeometryCollection.GeometryCount; i++) { IGeometry geometry = multiPatchGeometryCollection.get_Geometry(i); switch(geometry.GeometryType) { case (esriGeometryType.esriGeometryTriangleStrip): outlineGeometryCollection.AddGeometryCollection(ConstructTriangleStripOutline(geometry)); break; case (esriGeometryType.esriGeometryTriangleFan): outlineGeometryCollection.AddGeometryCollection(ConstructTriangleFanOutline(geometry)); break; case (esriGeometryType.esriGeometryTriangles): outlineGeometryCollection.AddGeometryCollection(ConstructTrianglesOutline(geometry)); break; case (esriGeometryType.esriGeometryRing): outlineGeometryCollection.AddGeometry(ConstructRingOutline(geometry), ref _missing, ref _missing); break; default: throw new Exception("Unhandled Geometry Type. " + geometry.GeometryType); } } return outlineGeometryCollection; }
public static IGeometry GetSelectGeometry(IMap pMap) { if (pMap == null) { return(null); } if (pMap.SelectionCount == 0) { return(null); } IGeometryBag pGeometryBag = new GeometryBagClass(); IGeometryCollection pGeomtryCol = (IGeometryCollection)pGeometryBag; IEnumFeature pEnumFeature = (IEnumFeature)pMap.FeatureSelection; IFeature pFeature = pEnumFeature.Next(); object obj = System.Reflection.Missing.Value; while (pFeature != null) { pGeomtryCol.AddGeometry(pFeature.ShapeCopy, ref obj, ref obj); pFeature = pEnumFeature.Next(); } pGeometryBag.Project(pMap.SpatialReference); return((IGeometry)pGeometryBag); }
/// <summary> /// Construct triangles outline /// </summary> /// <param name="trianglesGeometry">triangles geometry</param> /// <returns>object implements IGeometryCollection</returns> public static IGeometryCollection ConstructTrianglesOutline(IGeometry trianglesGeometry) { IGeometryCollection outlineGeometryCollection = new GeometryBagClass(); IPointCollection trianglesPointCollection = trianglesGeometry as IPointCollection; // Triangles: an unlinked set of triangles, where every three vertices completes a new triangle. if ((trianglesPointCollection.PointCount % 3) != 0) { throw new Exception("Triangles Geometry Point Count Must Be Divisible By 3. " + trianglesPointCollection.PointCount); } else { for (int i = 0; i < trianglesPointCollection.PointCount; i += 3) { IPointCollection outlinePointCollection = new PolylineClass(); outlinePointCollection.AddPoint(trianglesPointCollection.get_Point(i), ref missing, ref missing); outlinePointCollection.AddPoint(trianglesPointCollection.get_Point(i + 1), ref missing, ref missing); outlinePointCollection.AddPoint(trianglesPointCollection.get_Point(i + 2), ref missing, ref missing); // Simulate: Polygon.Close outlinePointCollection.AddPoint(trianglesPointCollection.get_Point(i), ref missing, ref missing); IGeometry outlineGeometry = outlinePointCollection as IGeometry; MakeZAware(outlineGeometry); outlineGeometryCollection.AddGeometry(outlineGeometry, ref missing, ref missing); } } return(outlineGeometryCollection); }
/// <summary> /// 获得指定图层的合并范围 为本次加的一个函数 /// </summary> /// <param name="strLyrName"></param> /// <param name="strWhere"></param> /// <param name="eFeatureType"></param> /// <param name="eGeometryType"></param> /// <returns></returns> public IGeometry GetLyrUnionPlygon(IList <IFeature> vFeaList) { if (vFeaList.Count < 1) { return(null); } //构造 IGeometryBag pGeometryBag = new GeometryBagClass(); IGeometryCollection pGeometryCol = pGeometryBag as IGeometryCollection; object obj = System.Type.Missing; //获得所有图形 for (int i = 0; i < vFeaList.Count; i++) { if (vFeaList[i].Shape != null && !vFeaList[i].Shape.IsEmpty) { pGeometryCol.AddGeometry(vFeaList[i].ShapeCopy, ref obj, ref obj); } } //构造合并 ITopologicalOperator pTopo = new PolygonClass(); pTopo.ConstructUnion(pGeometryCol as IEnumGeometry); IGeometry pGeometry = pTopo as IGeometry; return(pGeometry); }
private IGeometryCollection GenerateYardSticks(IGeometryCollection verticesColl) { IPoint startPT = new PointClass(); IPoint endPT = new PointClass(); IGeometryCollection yardstickColl = new GeometryBagClass(); ISegmentCollection yardsegColl = new PolylineClass(); object obj = Type.Missing; for (int i = 0; i < verticesColl.GeometryCount; i++) { if (i < verticesColl.GeometryCount - 1) { ILine pLine = new LineClass(); startPT = verticesColl.get_Geometry(i) as IPoint; endPT = verticesColl.get_Geometry(i + 1) as IPoint; pLine.PutCoords(startPT, endPT); yardsegColl.AddSegment(pLine as ISegment, ref obj, ref obj); } else { MessageBox.Show(i + " yardsticks generated"); } } IPolyline pPolyline = (IPolyline)yardsegColl; yardstickColl.AddGeometry(pPolyline, ref obj, ref obj); return(yardstickColl); }
public void MeasureBufferConstructionConstructBuffersPerformance() { const int iterations = 100; IEnumerable <IGeometry> sources = GetBufferInput(iterations); IBufferConstruction bufferConstruction = GetBufferConstruction(); IGeometryBag outputBag = new GeometryBagClass(); var watch = new Stopwatch(); watch.Start(); bufferConstruction.ConstructBuffers( new GeometryEnumerator <IGeometry>(sources), 10, (IGeometryCollection)outputBag); watch.Stop(); Assert.AreEqual(iterations, ((IGeometryCollection)outputBag).GeometryCount); Console.Out.WriteLine( "IBufferConstruction.ConstructBuffers: {0:N2} ms per geometry", (double)watch.ElapsedMilliseconds / iterations); }
public static IGeometry GetSearchGeometryFromGraphics(IGraphicsContainer graphics) { IGeometryCollection geometryBag = new GeometryBagClass(); IElement element; IGeometry geometry; graphics.Reset(); element = graphics.Next(); object before = Type.Missing; object after = Type.Missing; while (element != null) { geometry = element.Geometry; if (geometry is IPolygon) { geometryBag.AddGeometry(geometry, ref before, ref after); } element = graphics.Next(); } IGeometry searchGeometry = geometryBag as IGeometry; return(searchGeometry); }
public static void FlashLine(IEnumerable <IPoint> points) { var activeView = (ArcMap.Application.Document as IMxDocument)?.FocusMap as IActiveView; IGeometryBridge2 pGeoBrg = new GeometryEnvironment() as IGeometryBridge2; IPointCollection4 pPointColl = new PolylineClass(); var aWKSPointBuffer = new IPoint[points.Count()]; var i = 0; foreach (var point in points) { aWKSPointBuffer[i] = point; i++; } pGeoBrg.SetPoints(pPointColl, ref aWKSPointBuffer); var polyline = pPointColl as IPolyline; IGeometryCollection theGeomColl = new GeometryBagClass(); theGeomColl.AddGeometry(polyline); ITopologicalOperator theTopoOp = new PolylineClass(); theTopoOp.ConstructUnion((IEnumGeometry)theGeomColl); IGeometry flashGeometry = theTopoOp as IGeometry; if (flashGeometry != null) { EsriTools.ZoomToGeometry(activeView, polyline); EsriTools.FlashGeometry(activeView.ScreenDisplay, new IGeometry[] { polyline }); } }
private IPolygon DissolvePolygon(ISpatialReference spatialRef, Dictionary <string, IPolygon> originPolygonDict, string[] originStrArr) { IGeometry geometryBag = new GeometryBagClass(); var geoCollection = (IGeometryCollection)geometryBag; ((IGeometry)geoCollection).SpatialReference = spatialRef; for (int i = 0; i < originStrArr.Length; i++) { var originStr = originStrArr[i]; object missing = Type.Missing; //var polygon = (IPolygon)((IClone)originPolygonDict[originStr]).Clone(); geoCollection.AddGeometry(originPolygonDict[originStr], ref missing, ref missing); } // 找到的要素合并为一个要素 IPolygon outPolygon = new PolygonClass(); ITopologicalOperator topologicalOperator = (ITopologicalOperator)outPolygon; topologicalOperator.ConstructUnion((IEnumGeometry)geometryBag); return(outPolygon); }
public void FlashLineOnWorkingGraphics(int profileId, int lineId) { var curList = allGraphics[MilSpaceGraphicsTypeEnum.Session]; IGeometry flashGeometry = null; if (lineId > 0) { int elementId = lineId; var graphic = curList.FirstOrDefault(g => g.ProfileId == profileId && g.ElementId == elementId); if (graphic != null) { flashGeometry = graphic.Source; } } else { var graphics = curList.Where(g => g.ProfileId == profileId).Select(g => g.Source).ToList(); IGeometryCollection theGeomColl = new GeometryBagClass(); graphics.ForEach(pl => theGeomColl.AddGeometry(pl)); ITopologicalOperator theTopoOp = new PolylineClass(); theTopoOp.ConstructUnion((IEnumGeometry)theGeomColl); flashGeometry = theTopoOp as IGeometry; } if (flashGeometry != null) { EsriTools.FlashGeometry(activeView.ScreenDisplay, flashGeometry); activeView.Refresh(); } }
public static IGeometry GetSelectFeatureGeom(IMap pMap) { try { object obj = System.Reflection.Missing.Value; IGeometryBag pGeometryBag = new GeometryBagClass(); IGeometryCollection pGeomtryCol = (IGeometryCollection)pGeometryBag; ISelection pSelection = pMap.FeatureSelection; IEnumFeature pEnumFea = pSelection as IEnumFeature; IFeature pFea = pEnumFea.Next(); while (pFea != null) { if (pFea.Shape != null && pFea.Shape.GeometryType == esriGeometryType.esriGeometryPolygon) { pGeomtryCol.AddGeometry(pFea.Shape, ref obj, ref obj); } pFea = pEnumFea.Next(); } ITopologicalOperator pTopo = new PolygonClass(); pTopo.ConstructUnion(pGeomtryCol as IEnumGeometry); IGeometry pGeometry = pTopo as IGeometry; return(pGeometry); } catch { return(null); } }
/// <summary> /// Construct multi patch outline /// </summary> /// <param name="multiPatchGeometry">multi patch geometry</param> /// <returns>object implements IGeometryCollection</returns> public static IGeometryCollection ConstructMultiPatchOutline(IGeometry multiPatchGeometry) { IGeometryCollection outlineGeometryCollection = new GeometryBagClass(); IGeometryCollection multiPatchGeometryCollection = multiPatchGeometry as IGeometryCollection; for (int i = 0; i < multiPatchGeometryCollection.GeometryCount; i++) { IGeometry geometry = multiPatchGeometryCollection.get_Geometry(i); switch (geometry.GeometryType) { case esriGeometryType.esriGeometryTriangleStrip: outlineGeometryCollection.AddGeometryCollection(ConstructTriangleStripOutline(geometry)); break; case esriGeometryType.esriGeometryTriangleFan: outlineGeometryCollection.AddGeometryCollection(ConstructTriangleFanOutline(geometry)); break; case esriGeometryType.esriGeometryTriangles: outlineGeometryCollection.AddGeometryCollection(ConstructTrianglesOutline(geometry)); break; case esriGeometryType.esriGeometryRing: outlineGeometryCollection.AddGeometry(ConstructRingOutline(geometry), ref missing, ref missing); break; default: throw new Exception("Unhandled Geometry Type. " + geometry.GeometryType); } } return(outlineGeometryCollection); }
/// <summary> /// Construct triangle fan outline /// </summary> /// <param name="triangleFanGeometry">triangle fan geometry</param> /// <returns>object implements IGeometryCollection</returns> public static IGeometryCollection ConstructTriangleFanOutline(IGeometry triangleFanGeometry) { IGeometryCollection outlineGeometryCollection = new GeometryBagClass(); IPointCollection triangleFanPointCollection = triangleFanGeometry as IPointCollection; // TriangleFan: a linked fan of triangles, where every vertex (after the first two) completes a new triangle. // A new triangle is always formed by connecting the new vertex with its immediate predecessor // and the first vertex of the part. for (int i = 2; i < triangleFanPointCollection.PointCount; i++) { IPointCollection outlinePointCollection = new PolylineClass(); outlinePointCollection.AddPoint(triangleFanPointCollection.get_Point(0), ref missing, ref missing); outlinePointCollection.AddPoint(triangleFanPointCollection.get_Point(i - 1), ref missing, ref missing); outlinePointCollection.AddPoint(triangleFanPointCollection.get_Point(i), ref missing, ref missing); // Simulate: Polygon.Close outlinePointCollection.AddPoint(triangleFanPointCollection.get_Point(0), ref missing, ref missing); IGeometry outlineGeometry = outlinePointCollection as IGeometry; MakeZAware(outlineGeometry); outlineGeometryCollection.AddGeometry(outlineGeometry, ref missing, ref missing); } return(outlineGeometryCollection); }
/// <summary> /// 把geometry合并起来,组成一个新的geometry,在缓冲buffer个单位 /// </summary> /// <param name="lstGeo">Geo列表</param> /// <param name="buffer">缓冲单位</param> /// <returns></returns> public static IGeometry GetUnionGeometry(IList <IGeometry> lstGeo, double buffer) { if (lstGeo.Count == 0) { return(null); } IGeometryBag pGeometryBag = new GeometryBagClass(); pGeometryBag.SpatialReference = lstGeo[0].SpatialReference; IGeometryCollection pGeometryCollection = pGeometryBag as IGeometryCollection; object obj = Type.Missing; foreach (IGeometry geo in lstGeo) { pGeometryCollection.AddGeometry(geo, ref obj, ref obj); } ITopologicalOperator UnionPolygon = new PolygonClass(); UnionPolygon.ConstructUnion(pGeometryCollection as ESRI.ArcGIS.Geometry.IEnumGeometry); IGeometry geoResult = UnionPolygon as IGeometry; ITopologicalOperator operatorTopo = geoResult as ITopologicalOperator; return(operatorTopo.Buffer(buffer)); }
private IGeometryCollection GetIntersectSameTypeFeatures(IFeatureClass pFc, IFeature pFeature, ISpatialFilter spatialFilter, IQueryFilter filter, string unionType, string unionValue, ref ArrayList fIDs) { object missing = Type.Missing; //object fID = pFeature.get_Value(pFeature.Fields.FindField("FID")); spatialFilter.GeometryField = "Shape"; spatialFilter.Geometry = pFeature.Shape; spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; if (currentFieldType == esriFieldType.esriFieldTypeString) { spatialFilter.WhereClause = unionType + " = " + "'" + unionValue + "'"; } else if (currentFieldType == esriFieldType.esriFieldTypeDate) { //filter.WhereClause = unionType + " = " + "'" + unionValue + "'"; } else { spatialFilter.WhereClause = unionType + " = " + unionValue; } filter = spatialFilter; IGeometryCollection pGeoCollection = new GeometryBagClass() as IGeometryCollection; IFeatureCursor pFeatureCursor = pFc.Search(filter, true); IFeature pF = pFeatureCursor.NextFeature(); while (pF != null) { fIDs.Add(pF.get_Value(pF.Fields.FindField("FID"))); pGeoCollection.AddGeometry(pF.ShapeCopy, ref missing, ref missing); pF = pFeatureCursor.NextFeature(); } Marshal.ReleaseComObject(pFeatureCursor); return(pGeoCollection); }
/// <summary> /// 获得当前视图上的选择要素 /// ZQ 2011 1203 将点要素自动去除 只合并线和面要素 /// </summary> /// <param name="pMap"></param> /// <returns></returns> private IGeometry ConstructUnion(IMap pMap) { IGeometry pGeometry = null; try { IGeometryBag pGeometryBag = new GeometryBagClass(); IGeometryCollection pGeometryCol = pGeometryBag as IGeometryCollection; object obj = System.Type.Missing; ISelection pSelection = pMap.FeatureSelection; IEnumFeature pEnumFeature = pSelection as IEnumFeature; IFeature pFeature = pEnumFeature.Next(); while (pFeature != null) { ///排除点要素 if (pFeature.ShapeCopy.GeometryType != esriGeometryType.esriGeometryPoint && pFeature.ShapeCopy.GeometryType != esriGeometryType.esriGeometryMultipoint) { if (!pFeature.ShapeCopy.IsEmpty) { pGeometryCol.AddGeometry(pFeature.ShapeCopy, ref obj, ref obj); } } pFeature = pEnumFeature.Next(); } //构造合并 ITopologicalOperator pTopo = new PolygonClass(); pTopo.ConstructUnion(pGeometryCol as IEnumGeometry); pGeometry = pTopo as IGeometry; return(pGeometry); } catch { return(pGeometry = null); } }
/// <summary> /// union几个面要素 /// </summary> /// <param name="lstGeometry">需要操作的面要素集合</param> /// <returns>返回union后的图形</returns> public static IGeometry GetUnion(List <IGeometry> lstGeometry) { IGeometryBag pGeoBag = new GeometryBagClass(); IGeometryCollection pGeoCol = pGeoBag as IGeometryCollection; if (lstGeometry.Count < 1) { return(null); } if (lstGeometry[0].SpatialReference != null) { pGeoBag.SpatialReference = lstGeometry[0].SpatialReference; } object obj = System.Type.Missing; for (int i = 0; i < lstGeometry.Count; i++) { IGeometry pTempGeo = lstGeometry[i]; pGeoCol.AddGeometry(pTempGeo, ref obj, ref obj); } ISpatialIndex pSI = pGeoBag as ISpatialIndex; pSI.AllowIndexing = true; pSI.Invalidate(); ITopologicalOperator pTopo = new PolygonClass(); pTopo.ConstructUnion(pGeoBag as IEnumGeometry); IGeometry pGeo = pTopo as IGeometry; return(pGeo); }
public override bool Check(ref List<Error> checkResult) { IQueryFilter pQueryFilter = new QueryFilterClass(); pQueryFilter.WhereClause = m_structPara.strWhereClause; //����������ѯ IFeatureCursor ipFeatCursor = pSrcFeatClass.Search(pQueryFilter, true); IFeature ipFeature = ipFeatCursor.NextFeature(); IGeometryCollection pGeometryCollection = new GeometryBagClass(); ///��ȡ�����������geometry while (ipFeature != null) { IGeometry ipGeometry = ipFeature.Shape; if (ipGeometry == null) { ipFeature = ipFeatCursor.NextFeature(); continue; } object Missing = Type.Missing; pGeometryCollection.AddGeometry(ipGeometry, ref Missing, ref Missing); ipFeature = ipFeatCursor.NextFeature(); } ISpatialIndex pSpatialIndex = (ISpatialIndex)pGeometryCollection; pSpatialIndex.AllowIndexing = true; pSpatialIndex.Invalidate(); ///��������ͼ������ص��Ŀռ��ѯ ISpatialFilter pSpatialFilter = new SpatialFilterClass(); pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelOverlaps; ///�����GeometryCollection����spatialfilter pSpatialFilter.Geometry = (IGeometry)pGeometryCollection; string Fields = "OBJECTID,Shape"; pSpatialFilter.SubFields = Fields; IFeatureCursor ipResultFtCur = pRelFeatClass.Search(pSpatialFilter, true); //�������� List<Error> pRuleResult = new List<Error>(); AddResult(ref pRuleResult, ipResultFtCur); checkResult = pRuleResult; if (ipResultFtCur != null) { Marshal.ReleaseComObject(ipResultFtCur); ipResultFtCur = null; } if (pSrcFeatClass != null) { Marshal.ReleaseComObject(pSrcFeatClass); pSrcFeatClass = null; } if (pRelFeatClass != null) { Marshal.ReleaseComObject(pRelFeatClass); pRelFeatClass = null; } return true; }
private void iSpatialFilterGeometryBagToolStripMenuItem_Click(object sender, EventArgs e) { Stopwatch myWatch = Stopwatch.StartNew(); //从MapControl中获取的点图层 IFeatureLayer pointFeatureLayer = axMapControl1.get_Layer(0) as IFeatureLayer; IFeatureSelection pointFeatureSelection = pointFeatureLayer as IFeatureSelection; //从MapControl中获取的面图层 IFeatureLayer polygonFeatureLayer = axMapControl1.get_Layer(1) as IFeatureLayer; //构建GeometryBag IGeometryBag geometryBag = new GeometryBagClass(); IGeometryCollection geometryCollection = (IGeometryCollection)geometryBag; IGeoDataset geoDataset = (IGeoDataset)polygonFeatureLayer; ISpatialReference spatialReference = geoDataset.SpatialReference; //一定要给GeometryBag赋空间参考 geometryBag.SpatialReference = spatialReference; IQueryFilter queryFilter = new QueryFilterClass(); //Search如果返回属性值的话设置SubFields会提高效率 queryFilter.SubFields = "Shape"; //遍历面要素类,逐一获取Geometry并添加到GeometryBag中 IFeatureCursor cursor = polygonFeatureLayer.Search(queryFilter, true); IFeature polygonFeature = null; while ((polygonFeature = cursor.NextFeature()) != null) { geometryCollection.AddGeometry(polygonFeature.ShapeCopy); } //为GeometryBag生成空间索引,以提高效率 ISpatialIndex spatialIndex = (ISpatialIndex)geometryBag; spatialIndex.AllowIndexing = true; spatialIndex.Invalidate(); //构建空间查询 ISpatialFilter spatialFilter = new SpatialFilterClass(); spatialFilter.Geometry = geometryBag; spatialFilter.GeometryField = pointFeatureLayer.FeatureClass.ShapeFieldName; spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains; //选择的话可以不设置SubFields pointFeatureSelection.SelectFeatures(spatialFilter as IQueryFilter, esriSelectionResultEnum.esriSelectionResultAdd, false); int count = pointFeatureSelection.SelectionSet.Count; axMapControl1.Refresh(); //释放游标 System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cursor); myWatch.Stop(); string time = myWatch.Elapsed.TotalSeconds.ToString(); MessageBox.Show("The selected point count is " + count.ToString() + "! and " + time + " Seconds"); }
private void btnOK_Click(object sender, EventArgs e) { //生成被查询的图层集以传入查询结果窗体 lstQueryedLayer = new List <ILayer>(); foreach (ListViewItem lvi in lstLayer.Items) { if (lvi.Checked == true) { lstQueryedLayer.Add(lvi.Tag as ILayer); } } //生成选择的查询图层的搜索图形 IFeatureLayer pFL = null; foreach (ILayer pLayer in lstSelectLayer) { if (pLayer.Name == cboxSearchLayer.Text) { pFL = pLayer as IFeatureLayer; } } IGeometryBag gmBag = new GeometryBagClass(); gmBag.SpatialReference = pMap.SpatialReference;//定义空间参考,否则加入的图形将失去参考 IGeometryCollection gmCollection = gmBag as IGeometryCollection; if (rdSelect.Checked)//如果单选框 选择的要素是选中状态 { ISelectionSet pSelSet = (pFL as IFeatureSelection).SelectionSet; ICursor pCursor; pSelSet.Search(null, false, out pCursor); IFeature pFeature = (pCursor as IFeatureCursor).NextFeature(); object obj = Type.Missing; while (pFeature != null) { gmCollection.AddGeometry(pFeature.ShapeCopy, ref obj, ref obj); pFeature = (pCursor as IFeatureCursor).NextFeature(); } } else//如果单选框 全部要素是选择状态 { IFeatureCursor pFeaCursor = pFL.FeatureClass.Search(null, false); IFeature pFea = pFeaCursor.NextFeature(); object obj = Type.Missing; while (pFea != null) { gmCollection.AddGeometry(pFea.ShapeCopy, ref obj, ref obj); pFea = pFeaCursor.NextFeature(); } } ISpatialIndex pSI = gmBag as ISpatialIndex;//重建索引 pSI.AllowIndexing = true; pSI.Invalidate(); GeometryBag = gmBag; }
public void LearningTestBufferConstructionHandlingEmptyInput() { var inputBag = new GeometryBagClass(); IBufferConstruction bufferConstruction = GetBufferConstruction(); IGeometryBag outputBag = new GeometryBagClass(); bufferConstruction.ConstructBuffers(inputBag, 10, (IGeometryCollection)outputBag); Assert.AreEqual(0, ((IGeometryCollection)outputBag).GeometryCount); }
/// <summary> /// 将多个图形合并(Union)成一个图形(使用GeometryBag提高合并效率) /// </summary> /// <param name="geometries">需要合并的几何图形(注意这些图形必须是相同的几何类型)</param> /// <returns></returns> public static IGeometry UnionGeometryEx(this IEnumerable <IGeometry> geometries) { IGeometry geometryBag = new GeometryBagClass(); geometryBag.SpatialReference = geometries.First().SpatialReference; IGeometryCollection geometryCollection = geometryBag as IGeometryCollection; foreach (var geometry in geometries) { object missing = Type.Missing; geometryCollection.AddGeometry(geometry, ref missing, ref missing); } return(UnionGeometryEx(geometryBag, geometries.First().GeometryType)); }
/// <summary> /// 获得指定图层的合并范围 为本次加的一个函数 /// </summary> /// <param name="strLyrName"></param> /// <param name="strWhere"></param> /// <param name="eFeatureType"></param> /// <param name="eGeometryType"></param> /// <returns></returns> public IEnvelope GetLyrUnionEnvelope(IList <IFeature> vFeaList) { if (vFeaList.Count < 1) { return(null); } //构造 IEnvelope pEnv = null; IGeometryBag pGeometryBag = new GeometryBagClass(); IGeometryCollection pGeometryCol = pGeometryBag as IGeometryCollection; object obj = System.Type.Missing; //获得所有图形 for (int i = 0; i < vFeaList.Count; i++) { if (vFeaList[i].Shape != null && !vFeaList[i].Shape.IsEmpty) { if (pEnv == null) { pEnv = new EnvelopeClass(); pEnv.XMin = vFeaList[i].ShapeCopy.Envelope.XMin; pEnv.XMax = vFeaList[i].ShapeCopy.Envelope.XMax; pEnv.YMin = vFeaList[i].ShapeCopy.Envelope.YMin; pEnv.YMax = vFeaList[i].ShapeCopy.Envelope.YMax; } else { if (pEnv.XMin > vFeaList[i].ShapeCopy.Envelope.XMin) { pEnv.XMin = vFeaList[i].ShapeCopy.Envelope.XMin; } if (pEnv.XMax < vFeaList[i].ShapeCopy.Envelope.XMax) { pEnv.XMax = vFeaList[i].ShapeCopy.Envelope.XMax; } if (pEnv.YMin > vFeaList[i].ShapeCopy.Envelope.YMin) { pEnv.YMin = vFeaList[i].ShapeCopy.Envelope.YMin; } if (pEnv.YMax < vFeaList[i].ShapeCopy.Envelope.YMax) { pEnv.YMax = vFeaList[i].ShapeCopy.Envelope.YMax; } } } } //构造合并 return(pEnv); }
/// <summary> /// 将多个图形合并(Union)成一个图形(使用GeometryBag提高合并效率) /// </summary> /// <param name="featureClass">从中查询图形的要素类</param> /// <param name="whereCluase">查询条件</param> /// <returns></returns> public static IGeometry UnionGeometryEx(this IFeatureClass featureClass, string whereCluase = null) { IGeometry geometryBag = new GeometryBagClass(); geometryBag.SpatialReference = ((IGeoDataset)featureClass).SpatialReference; IGeometryCollection geometryCollection = geometryBag as IGeometryCollection; featureClass.QueryFeatures(whereCluase, f => { object missing = Type.Missing; geometryCollection.AddGeometry(f.ShapeCopy, ref missing, ref missing); }); return(UnionGeometryEx(geometryBag, featureClass.ShapeType)); }
private void createGrapicAndZoomTo(string capakeyResponse, datacontract.geojson Geom) { IRgbColor inClr = new RgbColorClass() { Red = 0, Blue = 100, Green = 0 };; IRgbColor outLine = new RgbColorClass() { Red = 0, Blue = 200, Green = 0, Transparency = 240 }; if (Geom.type == "MultiPolygon") { datacontract.geojsonMultiPolygon muniPolygons = JsonConvert.DeserializeObject <datacontract.geojsonMultiPolygon>(capakeyResponse); IGeometryCollection multiPoly = new GeometryBagClass(); clearGraphics(); foreach (datacontract.geojsonPolygon poly in muniPolygons.toPolygonList()) { IPolygon lbPoly = geopuntHelper.geojson2esriPolygon(poly, (int)dataHandler.CRS.Lambert72); lbPoly.SimplifyPreserveFromTo(); IGeometry prjGeom = geopuntHelper.Transform((IGeometry)lbPoly, map.SpatialReference); IElement muniGrapic = geopuntHelper.AddGraphicToMap(map, prjGeom, inClr, outLine, 2, true); graphics.Add(muniGrapic); multiPoly.AddGeometry(prjGeom); } view.Extent = ((IGeometryBag)multiPoly).Envelope; view.Refresh(); } else if (Geom.type == "Polygon") { datacontract.geojsonPolygon municipalityPolygon = JsonConvert.DeserializeObject <datacontract.geojsonPolygon>(capakeyResponse); IPolygon lbPoly = geopuntHelper.geojson2esriPolygon(municipalityPolygon, (int)dataHandler.CRS.Lambert72); lbPoly.SimplifyPreserveFromTo(); IPolygon prjPoly = (IPolygon)geopuntHelper.Transform((IGeometry)lbPoly, map.SpatialReference); view.Extent = prjPoly.Envelope; clearGraphics(); IElement muniGrapic = geopuntHelper.AddGraphicToMap(map, (IGeometry)prjPoly, inClr, outLine, 3, true); graphics.Add(muniGrapic); view.Refresh(); } }
/// <summary> /// 筛选要素类中,与指定图形满足一定空间关系的要素(空间筛选时添加空间索引) /// (参考:http://blog.csdn.net/lanpy88/article/details/7173063) /// </summary> /// <param name="featureClass">从中筛选要素的要素类(A)</param> /// <param name="geometry">过滤条件图形(B)</param> /// <param name="spatialRefEnum">空间关系类型(举例:esriSpatialRelContains表示A包含B)</param> /// <param name="whereClause">查询条件</param> /// <returns></returns> public static List <IFeature> FilterFeaturesEx(this IFeatureClass featureClass, IGeometry geometry, esriSpatialRelEnum spatialRefEnum, string whereClause = "") { IGeometryBag geometryBag = new GeometryBagClass(); IGeometryCollection geometryCollection = (IGeometryCollection)geometryBag; geometryBag.SpatialReference = ((IGeoDataset)featureClass).SpatialReference; //一定要给GeometryBag赋空间参考 geometryCollection.AddGeometry(geometry); //为GeometryBag生成空间索引,以提高效率 ISpatialIndex spatialIndex = (ISpatialIndex)geometryBag; spatialIndex.AllowIndexing = true; spatialIndex.Invalidate(); return(FilterFeatures(featureClass, geometry, spatialRefEnum, whereClause)); }
private List <IElement> CreateElementAois(List <IPolygon> polygons, out IEnvelope encompassingEnvelope) { var rgbColor = new RgbColorClass { Red = 0, Green = 0, Blue = 255, Transparency = 200 }; var geometryBag = new GeometryBagClass(); geometryBag.SpatialReference = ArcMap.Document.FocusMap.SpatialReference; IGeometryCollection geometryCollection = geometryBag; var elements = new List <IElement>(); foreach (var polygon in polygons) { geometryCollection.AddGeometry(polygon); IElement element = null; // Polygon elements ILineSymbol lineSymbol = new SimpleLineSymbolClass(); lineSymbol.Color = rgbColor; lineSymbol.Width = 2.0; ISimpleFillSymbol simpleFillSymbol = new SimpleFillSymbolClass(); simpleFillSymbol.Color = rgbColor; simpleFillSymbol.Style = esriSimpleFillStyle.esriSFSNull; simpleFillSymbol.Outline = lineSymbol; IFillShapeElement fillShapeElement = new PolygonElementClass(); fillShapeElement.Symbol = simpleFillSymbol; element = (IElement)fillShapeElement; // Explicit Cast element.Geometry = polygon; elements.Add(element); } // Create the polygon that will be the union of the features returned from the search cursor. // The spatial reference of this feature does not need to be set ahead of time. The // ConstructUnion method defines the constructed polygon's spatial reference to be the same as // the input geometry bag. ITopologicalOperator unionedPolygon = new PolygonClass(); unionedPolygon.ConstructUnion(geometryBag); var masterPoly = (IPolygon)unionedPolygon; encompassingEnvelope = masterPoly.Envelope; return(elements); }
private IGeometry BufferExtAndIntBoundary(IPolygon4 polygon, double bufferDistance, bool draw) { IGeometry bndBuffer; object obj = Type.Missing; IGeometryCollection bufferGeometries = new GeometryBagClass() as IGeometryCollection; IGeometryBag exteriorRings = polygon.ExteriorRingBag; IEnumGeometry exteriorRingsEnum = exteriorRings as IEnumGeometry; exteriorRingsEnum.Reset(); IRing currentExteriorRing = exteriorRingsEnum.Next() as IRing; while (currentExteriorRing != null) { bndBuffer = BufferBoundary(currentExteriorRing, bufferDistance, false); bufferGeometries.AddGeometry(bndBuffer, ref obj, ref obj); //IPolygon4.get_InteriorRingBag should be used instead of IPolygon.QueryInteriorRings, //which does not work in .NET because of C-Style Arrays IGeometryBag interiorRings = polygon.get_InteriorRingBag(currentExteriorRing); IEnumGeometry interiorRingsEnum = interiorRings as IEnumGeometry; interiorRingsEnum.Reset(); IRing currentInteriorRing = interiorRingsEnum.Next() as IRing; while (currentInteriorRing != null) { bndBuffer = BufferBoundary(currentInteriorRing, bufferDistance, false); bufferGeometries.AddGeometry(bndBuffer, ref obj, ref obj); currentInteriorRing = interiorRingsEnum.Next() as IRing; } currentExteriorRing = exteriorRingsEnum.Next() as IRing; } ITopologicalOperator topoBufferGeometries = bufferGeometries as ITopologicalOperator; topoBufferGeometries.Simplify(); IPolygon buffPolygon = new PolygonClass(); ITopologicalOperator topoPolygon = buffPolygon as ITopologicalOperator; IEnumGeometry enumGeometry = bufferGeometries as IEnumGeometry; topoPolygon.ConstructUnion(enumGeometry); if (draw) { DrawGraphics(buffPolygon as IGeometry); } return(buffPolygon as IGeometry); }
public void FlashLineOnWorkingGraphics(IEnumerable <IGeometry> flashingGeometry) { var curList = allGraphics[MilSpaceGraphicsTypeEnum.Session]; IGeometry flashGeometry = null; IGeometryCollection theGeomColl = new GeometryBagClass(); flashingGeometry.ToList().ForEach(pl => theGeomColl.AddGeometry(pl)); ITopologicalOperator theTopoOp = new PolylineClass(); theTopoOp.ConstructUnion((IEnumGeometry)theGeomColl); flashGeometry = theTopoOp as IGeometry; if (flashGeometry != null) { EsriTools.FlashGeometry(activeView.ScreenDisplay, flashingGeometry); } }
/// <summary> /// Unions all extents /// </summary> /// <param name="map"></param> /// <returns>envelope</returns> internal IEnvelope UnionAllLayerExtents(IMap map) { var layers = map.get_Layers(); var layer = layers.Next(); var geomBag = new GeometryBagClass(); geomBag.SpatialReference = map.SpatialReference; var geomColl = (IGeometryCollection)geomBag; object MissingType = Type.Missing; while (layer != null) { if (layer.AreaOfInterest != null) { geomColl.AddGeometry(layer.AreaOfInterest, ref MissingType, ref MissingType); } layer = layers.Next(); } return(geomBag.Envelope); }
public void buildModel() { IGeometryBag geoBag = new GeometryBagClass(); IGeometryCollection geoColl = (IGeometryCollection)geoBag; IFeatureCursor ftCur = projectArea.Search(null, false); IFeature ftr = ftCur.NextFeature(); while (ftr != null) { geoColl.AddGeometry(ftr.Shape); ftr = ftCur.NextFeature(); } dgc = new dataGeneralConfusionMatirx(); dgc.getXTable(oModel); olabels = dgc.Labels.ToList(); xTable = dgc.XTable; oClmProp = dgc.GeneralConfusionMatrix.ColumnProportions; nCnts = new double[oClmProp.Length]; adjustXTable((IGeometry)geoBag); gc = new GeneralConfusionMatrix(xTable); kappa = gc.Kappa; ste = gc.StandardError; writeXTable(); }
/// <summary> /// 将要素类中的图形存放到GeometryBag /// </summary> /// <param name="featureClass"></param> /// <returns></returns> public static IGeometryBag AddToGeometryBag(this IFeatureClass featureClass) { //创建GoemetryBag IGeometryBag geometryBag = new GeometryBagClass(); IGeometryCollection geometryCollection = (IGeometryCollection)geometryBag; //给GeometryBag赋空间参考 ISpatialReference spatialReference = ((IGeoDataset)featureClass).SpatialReference; geometryBag.SpatialReference = spatialReference; //遍历面要素类,逐一获取Geometry并添加到GeometryBag中 IQueryFilter queryFilter = new QueryFilterClass(); queryFilter.SubFields = "Shape";//Search如果返回属性值的话设置SubFields会提高效率 IFeatureCursor cursor = featureClass.Search(queryFilter, true); IFeature feature; while ((feature = cursor.NextFeature()) != null) { geometryCollection.AddGeometry(feature.ShapeCopy); } return(geometryBag); }
//��˷�ٲ��ҹ����漰�ĵؿ� public static void UpStreamFindParcels(AxMapControl ppAxMapControl, IEnumNetEID pEnumResultEdges, IGeometricNetwork pGeoNetwork) { try { IFeatureLayer pFeatLayerSewerLines = FindFeatLayer("Sewer Lines", ppAxMapControl); IFeatureLayer pFeatLayerParcels = FindFeatLayer("Parcels", ppAxMapControl); //����ѡ���Sewer�������д������ΰ� IGeometryCollection pGeomBag = new GeometryBagClass(); object missing = Type.Missing; int lEID; int iUserClassID; int iUserID; int iUserSubID; INetElements pNetElements = pGeoNetwork.Network as INetElements; pEnumResultEdges.Reset(); IFeature pFeature; for (int j = 0; j <= pEnumResultEdges.Count - 1; j++) { lEID = pEnumResultEdges.Next(); pNetElements.QueryIDs(lEID, esriElementType.esriETEdge, out iUserClassID, out iUserID, out iUserSubID); pFeature = pFeatLayerSewerLines.FeatureClass.GetFeature(iUserID); pGeomBag.AddGeometry(pFeature.Shape, ref missing, ref missing); // MessageBox.Show(iUserClassID.ToString()+","+iUserID.ToString()+","+iUserSubID.ToString()); } //���пռ����˵��Ӳ��������ڲ��ҵؿ���Ϣ ISpatialFilter pSpatialFilter = new SpatialFilterClass(); pSpatialFilter.Geometry = pGeomBag as IGeometry; pSpatialFilter.GeometryField = "Shape"; pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; pSpatialFilter.SearchOrder = esriSearchOrder.esriSearchOrderSpatial; //��ý��浽�ĵؿ���Ϣ IFeatureCursor pFeatCursor = pFeatLayerParcels.FeatureClass.Search(pSpatialFilter, false); //���ӱ�ѡ��ĵؿ����ݵ���ͼ��ͼ��ͼ�������� ICompositeGraphicsLayer pComGraphicLayer = new CompositeGraphicsLayerClass(); ILayer pLayer = pComGraphicLayer as ILayer; pLayer.Name = "��Ӱ��ĵؿ�"; IGraphicsContainer pGraphicContainer = pComGraphicLayer as IGraphicsContainer; //������ѡ��ĵؿ鵽ͼ�������� ISimpleFillSymbol pSymFill = new SimpleFillSymbolClass(); IFillSymbol pFillSymbol = pSymFill as IFillSymbol; IRgbColor pRgbColor = new RgbColorClass(); pRgbColor.Red = 0; pRgbColor.Green = 200; pRgbColor.Blue = 100; pFillSymbol.Color = pRgbColor as IColor; ICartographicLineSymbol pCartoLine = new CartographicLineSymbolClass(); IRgbColor pRgbColor2 = new RgbColorClass(); pRgbColor2.Red = 100; pRgbColor2.Green = 200; pRgbColor2.Blue = 100; pCartoLine.Width = 2; pCartoLine.Color = pRgbColor2 as IColor; pFillSymbol.Outline = pCartoLine; //����������еؿ����������� IArray pFeatArray = new ArrayClass(); pFeature = pFeatCursor.NextFeature(); while (pFeature != null) { IElement pPolyElement = new PolygonElementClass(); IFillShapeElement pFillShapeElement = pPolyElement as IFillShapeElement; pPolyElement.Geometry = pFeature.Shape; pFillShapeElement.Symbol = pFillSymbol; pGraphicContainer.AddElement(pPolyElement, 0); pFeatArray.Add(pFeature); pFeature = pFeatCursor.NextFeature(); } ppAxMapControl.AddLayer(pGraphicContainer as ILayer); ppAxMapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null); //ma //frmUpstreamCreateOwnerList frmUpstreamCreateOwnerList1 = new frmUpstreamCreateOwnerList(ppAxMapControl,pFeatLayerParcels, pFeatArray); //frmUpstreamCreateOwnerList1.Show(); } catch (Exception eX) { MessageBox.Show(eX.Message); } }
public override bool Check(ref List<Hy.Check.Define.Error> checkResult) { //�õ�Ŀ��ͼ���ϵͼ���featureclass IFeatureClass pSrcFeatClass = null; IFeatureClass pRelFeatClass = null; IFeatureCursor ipFeatCursor = null; checkResult = new List<Error>(); try { string shapeFieldName; IFeature ipFeature; ISpatialFilter pSpatialFilter = new SpatialFilterClass(); //(CLSID_SpatialFilter); //��ȡ��Ҫ���пռ��ϵ��ѯ��ILayer IFeatureWorkspace ipFtWS = null; ipFtWS = (IFeatureWorkspace)this.m_BaseWorkspace; pSrcFeatClass = ipFtWS.OpenFeatureClass(strSrcLayer); pRelFeatClass = ipFtWS.OpenFeatureClass(strRelLayer); // 1. ���ÿռ��ϵ if (!m_pPara.bCustomRel) // ʹ��engineԤ����Ŀռ��ϵ { pSpatialFilter.SpatialRel = m_pPara.eSpatialRel; } else //�Զ���ռ��ϵ { pSpatialFilter.SpatialRelDescription = m_pPara.strSpatialRel; } // 2.���ù��˼��� shapeFieldName = pSrcFeatClass.ShapeFieldName; pSpatialFilter.GeometryField = shapeFieldName; // 3.����ѡ���Ⱥ��ϵ����Ȼ��PGDB�����ã�������Ҳ����������� // Sets the order in which spatial searches are applied by the RDBMS (ArcSDE). //pSpatialFilter.put_SearchOrder(esriSearchOrderSpatial); // 4.����where��� if (m_pPara.strWhereClause.Length > 0) //hehyע�ͣ�2008��2��1�գ������ж�������ΪpSpatialFilter.SpatialRel = m_pPara.eSpatialRel; { pSpatialFilter.WhereClause = m_pPara.strWhereClause; } //pSpatialFilter.SpatialRel = m_pPara.eSpatialRel; // 5.Ŀ�������һ�����GeometryCollection IGeometryCollection pGeometryCollection = new GeometryBagClass(); //(CLSID_GeometryBag); IQueryFilter pQueryFilter = new QueryFilterClass(); //(CLSID_QueryFilter); string SubFields = "Shape"; pQueryFilter.SubFields = SubFields; ipFeatCursor = pRelFeatClass.Search(pQueryFilter, true); ipFeature = ipFeatCursor.NextFeature(); while (ipFeature != null) { IGeometry ipGeometry = ipFeature.Shape; if (ipGeometry == null) { ipFeature = ipFeatCursor.NextFeature(); continue; } object Missing = Type.Missing; if (!(m_pPara.bBuffer)) //���û����� { pGeometryCollection.AddGeometry(ipGeometry, ref Missing, ref Missing); } else //ʹ�û��� { ITopologicalOperator ipTopo = (ITopologicalOperator)ipGeometry; ipTopo.Simplify(); IGeometry ipGeobuffer = ipTopo.Buffer(m_pPara.dBuffer); pGeometryCollection.AddGeometry(ipGeobuffer, ref Missing, ref Missing); } ipFeature = ipFeatCursor.NextFeature(); } ISpatialIndex pSpatialIndex = (ISpatialIndex)pGeometryCollection; pSpatialIndex.AllowIndexing = true; pSpatialIndex.Invalidate(); // 6.�����GeometryCollection����spatialfilter pSpatialFilter.Geometry = (IGeometry)pGeometryCollection; // 7.Ŀ��ͼ���в������ɵ�spatialfilter���в�ѯ IFeatureCursor ipResultFtCur; string Fields = "OBJECTID,Shape"; pSpatialFilter.SubFields = Fields; //IQueryFilter queryFilter = new QueryFilterClass(); //queryFilter = (IQueryFilter) pSpatialFilter; ipResultFtCur = pSrcFeatClass.Search(pSpatialFilter, true); // 8.�������� AddResult(ref checkResult, ipResultFtCur); } catch (Exception ex) { return false; } finally { if (ipFeatCursor != null) { Marshal.ReleaseComObject(ipFeatCursor); ipFeatCursor = null; } if (pSrcFeatClass != null) { Marshal.ReleaseComObject(pSrcFeatClass); pSrcFeatClass = null; } if (pRelFeatClass != null) { Marshal.ReleaseComObject(pRelFeatClass); pRelFeatClass = null; } } return true; }
public bool HasParallelCurveMatchFeatures(IFeatureClass FeatureClass, IPolycurve inPolycurve, string WhereClause, double AngleToleranceTangentCompareInDegrees, double OrthogonalSearchDistance, out int outFoundLinesCount, out int outFoundParallelCurvesCount, ref List<string> CurveInfoFromNeighbours) { outFoundLinesCount = 0; outFoundParallelCurvesCount = 0; ILine pOriginalChord = new Line(); pOriginalChord.PutCoords(inPolycurve.FromPoint, inPolycurve.ToPoint); IVector3D vecOriginalSelected = new Vector3DClass(); vecOriginalSelected.PolarSet(pOriginalChord.Angle, 0, 1); int idxRadius = FeatureClass.FindField("RADIUS"); if (idxRadius == -1) return false; int idxCenterPointID = FeatureClass.FindField("CENTERPOINTID"); if (idxCenterPointID == -1) return false; object val = null; IGeometryBag pGeomBag = new GeometryBagClass(); IGeometryCollection pGeomColl = (IGeometryCollection)pGeomBag; IGeometry MultiPartPolyLine = new PolylineClass(); //qi IGeoDataset pGeoDS = (IGeoDataset)FeatureClass; ISpatialReference spatialRef = pGeoDS.SpatialReference; MultiPartPolyLine.SpatialReference = spatialRef; IGeometryCollection geometryCollection2 = MultiPartPolyLine as IGeometryCollection; ILine pNormalLine = new Line(); //new for (int i = -1; i < 2; i = i + 2) { double dOffset = OrthogonalSearchDistance * i; inPolycurve.QueryNormal(esriSegmentExtension.esriNoExtension, 0.5, true, dOffset, pNormalLine); ILine pThisLine = new Line(); pThisLine.PutCoords(pNormalLine.FromPoint, pNormalLine.ToPoint); pGeomColl.AddGeometry(pThisLine); //Although each line is connected to the other, create a new path for each line //this allows for future changes in case the input needs to be altered to separate paths. ISegmentCollection newPath = new PathClass(); object obj = Type.Missing; newPath.AddSegment((ISegment)pThisLine, ref obj, ref obj); //The spatial reference associated with geometryCollection will be assigned to all incoming paths and segments. geometryCollection2.AddGeometry(newPath as IGeometry, ref obj, ref obj); } ISpatialFilter pSpatFilt = new SpatialFilter(); pSpatFilt.WhereClause = WhereClause; pSpatFilt.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; pSpatFilt.SearchOrder = esriSearchOrder.esriSearchOrderSpatial; pSpatFilt.Geometry = pGeomBag; IFeatureCursor pFeatCursLines = null; try { pFeatCursLines = FeatureClass.Search(pSpatFilt, false); } catch (Exception ex) { MessageBox.Show(ex.Message); return false; } IFeature pFeat = pFeatCursLines.NextFeature(); while (pFeat != null) { IGeometry pFoundLineGeom = pFeat.ShapeCopy; //if the feature has no radius attribute, skip. double dRadius = 0; int iCtrPoint = -1; val = pFeat.get_Value(idxRadius); if (val == DBNull.Value) dRadius = 0; else dRadius = (double)val; if (dRadius == 0) {//null or zero radius so skip. Marshal.ReleaseComObject(pFeat); pFeat = pFeatCursLines.NextFeature(); continue; } val = pFeat.get_Value(idxCenterPointID); if (val == DBNull.Value) {//null centrpointID so skip. Marshal.ReleaseComObject(pFeat); pFeat = pFeatCursLines.NextFeature(); continue; } iCtrPoint = (int)val; ITopologicalOperator6 pTopoOp6 = (ITopologicalOperator6)MultiPartPolyLine; IGeometry pResultGeom = pTopoOp6.IntersectEx(pFoundLineGeom, false, esriGeometryDimension.esriGeometry0Dimension); if (pResultGeom == null) { Marshal.ReleaseComObject(pFeat); pFeat = pFeatCursLines.NextFeature(); continue; } if (pResultGeom.IsEmpty) { Marshal.ReleaseComObject(pFeat); pFeat = pFeatCursLines.NextFeature(); continue; } ISegmentCollection pFoundLineGeomSegs = pFoundLineGeom as ISegmentCollection; bool bHasCurves = false; pFoundLineGeomSegs.HasNonLinearSegments(ref bHasCurves); if (!bHasCurves) { Marshal.ReleaseComObject(pFeat); pFeat = pFeatCursLines.NextFeature(); continue; } IPointCollection5 PtColl = (IPointCollection5)pResultGeom; if (PtColl.PointCount > 1) { Marshal.ReleaseComObject(pFeat); pFeat = pFeatCursLines.NextFeature(); continue; } IPolycurve pPolyCurve4Tangent = pFoundLineGeom as IPolycurve; for (int j = 0; j < PtColl.PointCount; j++) { IPoint p = PtColl.get_Point(j); IPoint outPoint = new Point(); double dDistanceAlong = 0; double dDistanceFromCurve = 0; bool bOffsetRight = true; //work out if the point is to the left or right of the original inPolycurve.QueryPointAndDistance(esriSegmentExtension.esriNoExtension, p, false, outPoint, ref dDistanceAlong, ref dDistanceFromCurve, ref bOffsetRight); ILine pTangent = new Line(); dDistanceAlong = 0; dDistanceFromCurve = 0; bool bOnRight = true; pPolyCurve4Tangent.QueryPointAndDistance(esriSegmentExtension.esriNoExtension, p, false, outPoint, ref dDistanceAlong, ref dDistanceFromCurve, ref bOnRight); pPolyCurve4Tangent.QueryTangent(esriSegmentExtension.esriNoExtension, dDistanceAlong, false, 100, pTangent); //compare the tangent bearing with the normal to check for orthogonality IVector3D vecTangent = new Vector3DClass(); vecTangent.PolarSet(pTangent.Angle, 0, 1); IVector3D vecNormal = new Vector3DClass(); vecNormal.PolarSet(pNormalLine.Angle, 0, 1); ILine pHitDistanceForRadiusDifference = new Line(); pHitDistanceForRadiusDifference.PutCoords(pNormalLine.FromPoint, outPoint); double dRadiusDiff = pHitDistanceForRadiusDifference.Length; double dDotProd = vecTangent.DotProduct(vecNormal); double dAngleCheck = Math.Acos(dDotProd) * 180 / Math.PI; //in degrees dAngleCheck = Math.Abs(dAngleCheck - 90); if (dAngleCheck < AngleToleranceTangentCompareInDegrees) { //work out concavity orientation with respect to the original line using the radius sign and dot product dDotProd = vecOriginalSelected.DotProduct(vecTangent); double dTangentCheck = Math.Acos(dDotProd) * 180 / Math.PI; // in degrees //dTangentCheck at this point should be close to 0 or 180 degrees. outFoundLinesCount++; bool bIsConvex = ((dTangentCheck < 90 && dRadius < 0 && !bOffsetRight) || (dTangentCheck > 90 && dRadius > 0 && !bOffsetRight) || (dTangentCheck < 90 && dRadius > 0 && bOffsetRight) || (dTangentCheck > 90 && dRadius < 0 && bOffsetRight)); double dUnitSignChange = 1; if (!bIsConvex) dUnitSignChange = -1; double dDerivedRadius = (Math.Abs(dRadius)) + dRadiusDiff * dUnitSignChange; dUnitSignChange = 1; //now compute inferred left/right for candidate if (bIsConvex && !bOffsetRight) dUnitSignChange = -1; if (!bIsConvex && bOffsetRight) dUnitSignChange = -1; dDerivedRadius = dDerivedRadius * dUnitSignChange; string sHarvestedCurveInfo = pFeat.OID.ToString() + "," + dDerivedRadius.ToString("#.000") + "," + iCtrPoint.ToString() + "," + dRadiusDiff.ToString("#.000"); CurveInfoFromNeighbours.Add(sHarvestedCurveInfo); } } Marshal.ReleaseComObject(pFeat); pFeat = pFeatCursLines.NextFeature(); } Marshal.FinalReleaseComObject(pFeatCursLines); bool bHasParallelCurveFeaturesNearby = (outFoundLinesCount > 0); return bHasParallelCurveFeaturesNearby; }
public static IGeometryCollection ConstructTriangleFanOutline(IGeometry triangleFanGeometry) { IGeometryCollection outlineGeometryCollection = new GeometryBagClass(); IPointCollection triangleFanPointCollection = triangleFanGeometry as IPointCollection; // TriangleFan: a linked fan of triangles, where every vertex (after the first two) completes a new triangle. // A new triangle is always formed by connecting the new vertex with its immediate predecessor // and the first vertex of the part. for (int i = 2; i < triangleFanPointCollection.PointCount; i++) { IPointCollection outlinePointCollection = new PolylineClass(); outlinePointCollection.AddPoint(triangleFanPointCollection.get_Point(0), ref _missing, ref _missing); outlinePointCollection.AddPoint(triangleFanPointCollection.get_Point(i - 1), ref _missing, ref _missing); outlinePointCollection.AddPoint(triangleFanPointCollection.get_Point(i), ref _missing, ref _missing); outlinePointCollection.AddPoint(triangleFanPointCollection.get_Point(0), ref _missing, ref _missing); //Simulate: Polygon.Close IGeometry outlineGeometry = outlinePointCollection as IGeometry; MakeZAware(outlineGeometry); outlineGeometryCollection.AddGeometry(outlineGeometry, ref _missing, ref _missing); } return outlineGeometryCollection; }
private IGeometry IntersectRestraintFilter(IFeatureClass targetFeatureClass, IGeometry baseGeometry = null) { if (baseGeometry == null) { baseGeometry = rootGeometry; } IGeometry filteredGeometry = null; ISpatialFilter filter = new SpatialFilterClass(); filter.Geometry = baseGeometry; filter.GeometryField = "SHAPE"; filter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; IFeatureCursor cursor = targetFeatureClass.Search(filter, false); IFeature feature = cursor.NextFeature(); if (feature == null) { return null; } filteredGeometry = feature.Shape; ITopologicalOperator tpop = filteredGeometry as ITopologicalOperator; IGeometryCollection geomCol = new GeometryBagClass(); while((feature = cursor.NextFeature()) != null) { geomCol.AddGeometry(feature.Shape); } tpop.ConstructUnion(geomCol as IEnumGeometry); return filteredGeometry; }
protected void MakeTxtFileOfJSONElevationResponses() { //return; string trailName= "'GDT'"; string sectionName = "'G'"; string startWaypointOID = "1418"; int distanceBetweenPoints = 10; IGeometryCollection geomCol = new GeometryBagClass(); WebClient client = new WebClient(); string path = ""; string samples = ""; IFeatureClass trailFC = null; IFeatureClass elevationFC = null; IFeatureClass waypointFC = null; GetFeatureClasses(ref trailFC, ref elevationFC, ref waypointFC); IQueryFilter qf = new QueryFilterClass(); qf.WhereClause = "OBJECTID = " + startWaypointOID; //qf.WhereClause = "NAME = " + trailName + " and SECTIONNAME = " + sectionName; IFeatureCursor feCur = waypointFC.Search(qf, false); IFeature startWaypoint = feCur.NextFeature(); Marshal.FinalReleaseComObject(feCur); Queue<IFeature> waypointsToProcess = new Queue<IFeature>(); waypointsToProcess.Enqueue(startWaypoint); HashSet<int> waypointsWeHaveSeen = new HashSet<int>(); while(waypointsToProcess.Count > 0) { IFeature waypointFe = waypointsToProcess.Dequeue(); waypointsWeHaveSeen.Add(waypointFe.OID); ISpatialFilter sf = new SpatialFilterClass(); sf.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; sf.GeometryField = "SHAPE"; sf.Geometry = waypointFe.Shape; feCur = trailFC.Search(sf, false); IFeature connectedTrail = feCur.NextFeature(); while (connectedTrail != null) { if (("'" + connectedTrail.get_Value(connectedTrail.Fields.FindField("NAME")) + "'" == trailName) && ("'" + connectedTrail.get_Value(connectedTrail.Fields.FindField("SECTIONNAME")) +"'" == sectionName)) { File.AppendAllText(@"c:\temp\connectedSegs.txt", Environment.NewLine + connectedTrail.OID.ToString()); geomCol.AddGeometry(connectedTrail.ShapeCopy); int fromID = Convert.ToInt16(connectedTrail.get_Value(connectedTrail.Fields.FindField("FROMWAYPOINT"))); int toID = Convert.ToInt16(connectedTrail.get_Value(connectedTrail.Fields.FindField("TOWAYPOINT"))); if (waypointsWeHaveSeen.Contains(fromID) == false) { waypointsToProcess.Enqueue(waypointFC.GetFeature(fromID)); } if (waypointsWeHaveSeen.Contains(toID) == false) { waypointsToProcess.Enqueue(waypointFC.GetFeature(toID)); } } connectedTrail = feCur.NextFeature(); } Marshal.FinalReleaseComObject(feCur); } //return; Type factoryType = Type.GetTypeFromProgID("esriGeometry.SpatialReferenceEnvironment"); System.Object obj = Activator.CreateInstance(factoryType); ISpatialReferenceFactory spatialReferenceFactory = obj as ISpatialReferenceFactory; ISpatialReference spatRef = spatialReferenceFactory.CreateGeographicCoordinateSystem(4326); //ISpatialReference existingSpatRef = geomCol.get_Geometry(0).SpatialReference; ISpatialReference existingSpatRef = startWaypoint.ShapeCopy.SpatialReference; /*IFeature trailFe = feCur.NextFeature(); ISpatialReference existingSpatRef = null; while (trailFe != null) { geomCol.AddGeometry(trailFe.ShapeCopy); if(existingSpatRef == null) { existingSpatRef = trailFe.ShapeCopy.SpatialReference; } trailFe = feCur.NextFeature(); }*/ IPointCollection newPolyline = new PolylineClass(); ((IGeometry)newPolyline).SpatialReference = startWaypoint.ShapeCopy.SpatialReference; HashSet<string> points = new HashSet<string>(); for(int i = 0 ; i < geomCol.GeometryCount; i++) { IPointCollection geomPntCol = geomCol.get_Geometry(i) as IPointCollection; for (int j = 0; j < geomPntCol.PointCount; j++ ) { IPoint pnt = geomPntCol.get_Point(j); string pntString = pnt.X + "," + pnt.Y; if(points.Contains(pntString) == false) { points.Add(pntString); pnt.SpatialReference = startWaypoint.ShapeCopy.SpatialReference; newPolyline.AddPoint(pnt); } } } IPolyline fullTrail = newPolyline as IPolyline; fullTrail.SpatialReference = startWaypoint.ShapeCopy.SpatialReference; //ITopologicalOperator unionedPolyline = new PolylineClass(); //unionedPolyline.ConstructUnion(geomCol as IEnumGeometry); //IPolyline fullTrail = unionedPolyline as IPolyline; Marshal.FinalReleaseComObject(feCur); IFeature fromPoint = waypointFC.GetFeature(Convert.ToInt16( startWaypointOID)); IProximityOperator proxOp = fromPoint.ShapeCopy as IProximityOperator; double fromPointDist = proxOp.ReturnDistance(fullTrail.FromPoint); if (proxOp.ReturnDistance(fullTrail.ToPoint) == 0) { fullTrail.ReverseOrientation(); } int dividePointIndex = 1; List<IPoint> pointsOnTrail = new List<IPoint>(); double totalDistance = 0; while(dividePointIndex * distanceBetweenPoints < fullTrail.Length) { IPoint outPoint = new PointClass(); fullTrail.QueryPoint(esriSegmentExtension.esriNoExtension, dividePointIndex * distanceBetweenPoints, false, outPoint); outPoint.SpatialReference = existingSpatRef; outPoint.Project(spatRef); pointsOnTrail.Add(outPoint); dividePointIndex++; } StringBuilder sb = new StringBuilder(); List<string> locationStrings = new List<string>(); int locationPointsInStringBuilder = 0; for (int i = 0; i < pointsOnTrail.Count; i++) { if(sb.Length > 0) { sb.Append("|"); } sb.Append(pointsOnTrail[i].Y); sb.Append(","); sb.Append(pointsOnTrail[i].X); locationPointsInStringBuilder++; if (locationPointsInStringBuilder > 33) { locationStrings.Add(sb.ToString()); sb = new StringBuilder(); locationPointsInStringBuilder = 0; } } locationStrings.Add(sb.ToString()); //FileStream fsw = File.OpenWrite(@"c:\temp\SectionAElevations.txt"); int counter = 0; foreach(string locString in locationStrings) { counter++; //FileStream fsw = File.OpenWrite(@"c:\temp\SectionAElevations.txt"); string address = "https://maps.googleapis.com/maps/api/elevation/json?locations=" + locString + "&key=AIzaSyBJlaYSBeJkYl_G2tInjNJBYmjJhaSulLA"; System.Threading.Thread.Sleep(1000); string reply = client.DownloadString(address); File.AppendAllText(@"c:\temp\Section" + sectionName + "Elevations.txt", reply + Environment.NewLine); } // https://maps.googleapis.com/maps/api/elevation/json?locations=39.7391536,-104.9847034|36.455556,-116.866667&key=AIzaSyC2WxuR5N1TKk5rfFrFQSd_IwMlg3TvVnM //string address = @"https://maps.googleapis.com/maps/api/elevation/json?path=" + path + "&samples=" + samples + "&key=AIzaSyC2WxuR5N1TKk5rfFrFQSd_IwMlg3TvVnM"; }
public static IGeometry unionAllFeature(List<IGeometry> geometryList) { if (geometryList.Count == 0) { return new PolygonClass(); } else if (geometryList.Count == 1) { return geometryList[0] as IGeometry; } else { IGeometry geom = geometryList[0] as IGeometry; ITopologicalOperator topoOp = geom as ITopologicalOperator; IGeometryCollection pGeoCol = new GeometryBagClass();//定义Geometry类集合 for (int i = 1; i < geometryList.Count; i++) { IGeometry tempGeom = geometryList[i] as IGeometry; pGeoCol.AddGeometry(tempGeom); } IEnumGeometry enumGeom = pGeoCol as IEnumGeometry; topoOp.ConstructUnion(enumGeom); return geom; } }
private IGeoDataset ConvertAndUnionWatershed(IGeoDataset tWatershedGDS) { //Convert the raster IGeodataset into a Polygon IFeatureClass, in a memory-workspace IWorkspace inMemFeatWksp = CreateInMemoryWorkspace(); //IWorkspaceFactory pWSF = new ShapefileWorkspaceFactory(); //IWorkspace pWS = pWSF.OpenFromFile(out_folder,0); string current = GetTimeStamp(DateTime.Now); string outname = "resultWatershed" + current; IFeatureClass tWaterShedPolyFC; IGeoDataset tInitialPolygons; try { IConversionOp pConversionOp = new ESRI.ArcGIS.GeoAnalyst.RasterConversionOp() as IConversionOp; tInitialPolygons = pConversionOp.RasterDataToPolygonFeatureData(tWatershedGDS, inMemFeatWksp, outname, false); tWaterShedPolyFC = tInitialPolygons as IFeatureClass; } catch { logger.LogMessage(ServerLogger.msgType.debug, "convert and union wshed", 8000, "Error in converting watershed to in-memory FC"); tWaterShedPolyFC = null; tInitialPolygons = null; } // attempt to add a CATCH_AREA field to the feature class bool setAreaOk = false; try { //setAreaOk = AddAreaField(tWaterShedPolyFC); setAreaOk = AddAField(tWaterShedPolyFC, "Total_Area", esriFieldType.esriFieldTypeDouble); } catch { logger.LogMessage(ServerLogger.msgType.debug, "convert and union wshed", 8000, "Error adding area field to output"); } IFeature tWaterShedFeature; // if there is more than one feature in the FC then union them using geometrybag if (tWaterShedPolyFC.FeatureCount(null) > 1) { logger.LogMessage(ServerLogger.msgType.infoStandard, "convert and union wshed", 8000, "Attempting to union multiple polygons..."); // there is more than one polygon i.e. diagonally connected. merge them into a single feature // with multiple rings using a geometrybag IGeometryBag tGeometryBag = new GeometryBagClass(); tGeometryBag.SpatialReference = tInitialPolygons.SpatialReference; IFeatureCursor tFCursor = tWaterShedPolyFC.Search(null, false); IGeometryCollection tGeomColl = tGeometryBag as IGeometryCollection; IFeature tCurrentFeature = tFCursor.NextFeature(); ITable tTable = tCurrentFeature.Table; while (tCurrentFeature != null) { object missing = Type.Missing; tGeomColl.AddGeometry(tCurrentFeature.Shape, ref missing, ref missing); tCurrentFeature = tFCursor.NextFeature(); } ITopologicalOperator tUnioned = new PolygonClass(); tUnioned.ConstructUnion(tGeometryBag as IEnumGeometry); logger.LogMessage(ServerLogger.msgType.infoStandard, "convert and union wshed", 8000, "Done with ConstructUnion, doing area"); try { IArea tmpArea = tUnioned as IArea; double tArea = tmpArea.Area; // delete the previously existing rows from the table tTable.DeleteSearchedRows(null); // replace them with a new row representing the unioned feature IRow tRow = tTable.CreateRow(); tRow.set_Value(tTable.FindField("SHAPE"), tUnioned); tRow.set_Value(tTable.FindField("ID"), -1); tRow.set_Value(tTable.FindField("GRIDCODE"), -1); if (setAreaOk) { tRow.set_Value(tTable.FindField("Total_Area"), tArea); } tRow.Store(); } catch (Exception ex) { logger.LogMessage(ServerLogger.msgType.error, "store unioned polygon", 8000, "Error setting fields of unioned polygon!" + ex.StackTrace + ex.Message); } } else { // There is only one polygon - i.e. there were not diagonally-disconnected bits // NB features are indexed starting at 1. Just for a laff. tWaterShedFeature = tWaterShedPolyFC.GetFeature(1); if (setAreaOk) { try { int tAreaFieldIdx = tWaterShedFeature.Fields.FindField("Total_Area"); IArea tArea = tWaterShedFeature.Shape as IArea; double tmpArea = tArea.Area; tWaterShedFeature.set_Value(tAreaFieldIdx, tmpArea); tWaterShedFeature.Store(); logger.LogMessage(ServerLogger.msgType.debug, "convert and union wshed", 8000, "Done adding area to one polygon"); } catch { logger.LogMessage(ServerLogger.msgType.debug, "convert and union wshed", 8000, "Error adding area field to single polygon output"); } } } return (IGeoDataset)tWaterShedPolyFC; }
public static IEnvelope GetGridBagEnvelope(List<GisDataAdapter> lstRows) { IEnvelope envelopeTotal = new EnvelopeClass(); IGeometryCollection geomCollection = new GeometryBagClass(); object before = Type.Missing; object after = Type.Missing; for (int i = 0; i < lstRows.Count; i++) { IGeometry geometry = lstRows[i].GetFieldValue((lstRows[i].DataObjectClass as IFeatureClass).ShapeFieldName) as IGeometry; geomCollection.AddGeometry(geometry, ref before, ref after); } envelopeTotal = (geomCollection as GeometryBag).Envelope; return envelopeTotal; }
private static IGeometry get_GraphicShape(IEnumElement theElements, int a_Dimensionality, bool multipart, ref IElementCollection elemCollection) { IGeometry theReturn = null; IGeometryCollection theGeomColl = null; object missing = Type.Missing; try { elemCollection.Clear(); if (theElements != null) { theElements.Reset(); IElement theElement = theElements.Next(); while (theElement != null) { if (theGeomColl == null) theGeomColl = new GeometryBagClass(); IGeometry theShape = null; if (theElement is IGroupElement) { theShape = get_GraphicShape(((IGroupElement)theElement).Elements, a_Dimensionality, multipart,ref elemCollection); } else if (theElement is ICircleElement || theElement is IPolygonElement || theElement is IRectangleElement || theElement is IEllipseElement || theElement is ILineElement || theElement is IMarkerElement) theShape = theElement.Geometry; if (theShape != null) theGeomColl.AddGeometry(theShape, ref missing, ref missing); elemCollection.Add(theElement,-1); theElement = theElements.Next(); } } if (theGeomColl != null && theGeomColl.GeometryCount > 0) { ITopologicalOperator theTopoOp = null; switch (a_Dimensionality) { case 0: if (multipart) { theTopoOp = new MultipointClass(); theTopoOp.ConstructUnion((IEnumGeometry)theGeomColl); } else theTopoOp = theGeomColl.get_Geometry(0) as ITopologicalOperator; break; case 1: theTopoOp = new PolylineClass(); theTopoOp.ConstructUnion((IEnumGeometry)theGeomColl); break; case 2: theTopoOp = new PolygonClass(); theTopoOp.ConstructUnion((IEnumGeometry)theGeomColl); break; } theReturn = theTopoOp as IGeometry; } } catch(Exception ex) { util.Logger.Write(" Descrip : Finding elements with a specific dimensionality. " + "\n Message : " + ex.Message + "\n StackTrc : " + ex.StackTrace,util.Logger.LogLevel.Debug); } return theReturn; }
private void Btnok_Click(object sender, EventArgs e) { if (m_mapControl.Map.SelectionCount == 0) { MessageBox.Show("����ѡ�����ѯҪ�أ�"); return; } IEnumFeature pEnumfeature; IFeature pFeature; IFeature newFeat; //ITopologicalOperator pToplogicalOper; //IPolygon pPolygon; double bufferDistence; if (m_mapControl.Map.SelectionCount == 0) { return; } bufferDistence = Convert.ToDouble(BufferText.Text); pEnumfeature = m_mapControl.Map.FeatureSelection as IEnumFeature; pEnumfeature.Reset(); pFeature = pEnumfeature.Next(); IFeatureClass pFeatureclass; FileInfo n = new FileInfo(textBox1.Text); string openpath = n.Directory.ToString();//ȡ·���ĸ�Ŀ¼���ڴ��µ�layer pFeatureclass = CreatNewShapefile(openpath, n.Name, m_mapControl.SpatialReference); //IFeatureBuffer pFeatureBuffer = pFeatureclass.CreateFeatureBuffer(); //IFeatureCursor pFeatureCursor = pFeatureclass.Insert(true); int iFieldAttribute = pFeatureclass.FindField("Text"); //while (pFeature != null) //{ // pToplogicalOper = pFeature.Shape as ITopologicalOperator; // pPolygon = new PolygonClass(); // pPolygon = pToplogicalOper.Buffer(bufferDistence) as IPolygon; // pFeatureBuffer.Shape = pPolygon; // //pFeatureBuffer.set_Value(iFieldAttribute, pFeature.OID); // pFeatureCursor.InsertFeature(pFeatureBuffer); // pFeature = pEnumfeature.Next(); //} //pFeatureCursor.Flush(); //ML�Ĵ��� IGeometryCollection inputGeom = new GeometryBagClass(); IGeometryBag geomBag = inputGeom as IGeometryBag; object missing = Type.Missing; while (pFeature != null) { inputGeom.AddGeometry(pFeature.ShapeCopy, ref missing, ref missing); pFeature = pEnumfeature.Next(); } IBufferConstruction bfCon = new BufferConstructionClass(); IBufferConstructionProperties bfConProp = bfCon as IBufferConstructionProperties; ISpatialReferenceFactory spatialRefFac = new SpatialReferenceEnvironmentClass(); bfConProp.EndOption = esriBufferConstructionEndEnum.esriBufferRound; bfConProp.SideOption = esriBufferConstructionSideEnum.esriBufferFull; bfConProp.ExplodeBuffers = false; bfConProp.OutsideOnly = false; bfConProp.GenerateCurves = true; bfConProp.UnionOverlappingBuffers = true; bfConProp.DensifyDeviation = -1; IGeometryCollection outGeom = new GeometryBagClass(); bfCon.ConstructBuffers(inputGeom as IEnumGeometry, bufferDistence, outGeom); for (int i = 0; i < outGeom.GeometryCount; i++) { newFeat = pFeatureclass.CreateFeature(); newFeat.Shape = outGeom.get_Geometry(i); newFeat.Store(); } newFeat = null; //���ͼ���map IFeatureLayer pOutputFeatureLayer; pOutputFeatureLayer = new FeatureLayerClass(); pOutputFeatureLayer.FeatureClass = pFeatureclass; pOutputFeatureLayer.Name = pFeatureclass.AliasName; m_mapControl.Map.AddLayer(pOutputFeatureLayer); this.Dispose(); }
// Execute: Execute the function given the array of the parameters public void Execute(IArray paramvalues, ITrackCancel trackcancel, IGPEnvironmentManager envMgr, IGPMessages message) { IFeatureClass outputFeatureClass = null; try { // get the input feature class IGPMultiValue inputFeatureClasses_Parameter = (IGPMultiValue)m_GPUtilities.UnpackGPValue(paramvalues.get_Element(0)); layer[] input_featureClasses = new layer[inputFeatureClasses_Parameter.Count]; for (int i = 0; i < inputFeatureClasses_Parameter.Count; i++) { IGPValue inputFeatureClass_Parameter = inputFeatureClasses_Parameter.get_Value(i); IFeatureClass inputFeatureClass; IQueryFilter inputQF; m_GPUtilities.DecodeFeatureLayer(inputFeatureClass_Parameter, out inputFeatureClass, out inputQF); input_featureClasses[i] = new layer() { featureclass = inputFeatureClass, qFilter = inputQF}; } if (input_featureClasses.Length == 0 || input_featureClasses.Any(w=> w.featureclass == null)) { message.AddError(2, "Could not open one or more input dataset."); return; } //IFields additionalFields = new FieldsClass(); //additionalFields.AddField(FEATURE_SOURCE_FIELD_NAME, esriFieldType.esriFieldTypeString); //additionalFields.AddField(FEATURE_ID_FIELD_NAME, esriFieldType.esriFieldTypeInteger); //additionalFields.AddField( // input_featureClasses[0].featureclass.Fields.get_Field( // input_featureClasses[0].featureclass.Fields.FindField( // input_featureClasses[0].featureclass.ShapeFieldName))); // create the output feature class IGPValue outputFeatureClass_Parameter = m_GPUtilities.UnpackGPValue(paramvalues.get_Element(1)); outputFeatureClass = GPHelperFunctions.CreateFeatureClass(outputFeatureClass_Parameter, envMgr); if (outputFeatureClass == null) { message.AddError(2, "Could not create output dataset."); return; } IGPString curveTypeParameter = (IGPString)m_GPUtilities.UnpackGPValue(paramvalues.get_Element(2)); ArcConstructionMethods method; if (!Enum.TryParse<ArcConstructionMethods>(curveTypeParameter.Value, true, out method)) { message.AddError(2, string.Format("The value {0} is not expected. Expected values are: {1}.", curveTypeParameter.Value, string.Join(",", Enum.GetNames(typeof(ArcConstructionMethods))))); return; } IStepProgressor stepPro = (IStepProgressor)trackcancel; GPHelperFunctions.dropSpatialIndex(outputFeatureClass); BoostVoronoi bv = new BoostVoronoi(100); double minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue; List<site_key> point_sites = new List<site_key>(); List<site_key> segment_sites = new List<site_key>(); for (short i = 0; i < input_featureClasses.Length; i++) { layer l = input_featureClasses[i]; int featcount = l.featureclass.FeatureCount(l.qFilter); stepPro.MinRange = 0; stepPro.MaxRange = featcount; stepPro.StepValue = (1); stepPro.Message = "Reading features"; stepPro.Position = 0; stepPro.Show(); IFeatureCursor cursor = null; IFeature row = null; try { cursor = l.featureclass.Search(l.qFilter, false); while ((row = cursor.NextFeature()) != null) { stepPro.Step(); IPoint point = row.Shape as IPoint; if (point != null) { double X = point.X; double Y = point.Y; minX = Math.Min(minX, X); maxX = Math.Max(maxX, X); minY = Math.Min(minY, Y); maxY = Math.Max(maxY, Y); bv.AddPoint(point.X, point.Y); point_sites.Add(new site_key(i, row.OID)); } IMultipoint multipoint = row.Shape as IMultipoint; if (multipoint != null) { IPointCollection pointCollection = (IPointCollection)multipoint; IEnumVertex vertices = pointCollection.EnumVertices; IPoint vertex = null; int part, index; vertices.Next(out vertex, out part, out index); minX = Math.Min(minX, multipoint.Envelope.XMin); maxX = Math.Max(maxX, multipoint.Envelope.XMax); minY = Math.Min(minY, multipoint.Envelope.YMin); maxY = Math.Max(maxY, multipoint.Envelope.YMax); while (vertex != null) { bv.AddPoint(vertex.X, vertex.Y); point_sites.Add(new site_key(i, row.OID)); vertices.Next(out vertex, out part, out index); } } IPolyline polyline = row.Shape as IPolyline; if (polyline != null) { double fromX = polyline.FromPoint.X; double fromY = polyline.FromPoint.Y; double toX = polyline.ToPoint.X; double toY = polyline.ToPoint.Y; if (toX < fromX) { minX = Math.Min(minX, toX); maxX = Math.Max(maxX, fromX); } else { minX = Math.Min(minX, fromX); maxX = Math.Max(maxX, toX); } if (toY < fromY) { minY = Math.Min(minY, toY); maxY = Math.Max(maxY, fromY); } else { minY = Math.Min(minY, fromY); maxY = Math.Max(maxY, toY); } bv.AddSegment( polyline.FromPoint.X, polyline.FromPoint.Y, polyline.ToPoint.X, polyline.ToPoint.Y ); segment_sites.Add(new site_key(i, row.OID)); } Marshal.ReleaseComObject(row); } } finally { if (row != null) Marshal.ReleaseComObject(row); if (cursor != null) Marshal.ReleaseComObject(cursor); stepPro.Hide(); } } message.AddMessage(String.Format("{0}, {1} -> {2}, {3}", minX, minY, maxX, maxY)); int width = Math.Max((int)((maxX - minX) * 0.1), 1); int height = Math.Max((int)((maxY - minY) * 0.1), 1); maxX = maxX + width; minX = minX - width; maxY = maxY + height; minY = minY - height; message.AddMessage(String.Format("{0}, {1} -> {2}, {3}", minX, minY, maxX, maxY)); bv.AddSegment(minX, minY, maxX, minY); segment_sites.Add(new site_key(-1, -1)); bv.AddSegment(maxX, minY, maxX, maxY); segment_sites.Add(new site_key(-1, -1)); bv.AddSegment(maxX, maxY, minX, maxY); segment_sites.Add(new site_key(-1, -1)); bv.AddSegment(minX, maxY, minX, minY); segment_sites.Add(new site_key(-1, -1)); stepPro.Message = "Solve Voronoi"; stepPro.MaxRange = 0; stepPro.MaxRange = 0; stepPro.Show(); bv.Construct(); stepPro.Hide(); int featureSourceIndx = outputFeatureClass.Fields.FindField(FEATURE_SOURCE_FIELD_NAME); int featureIDIndx = outputFeatureClass.Fields.FindField(FEATURE_ID_FIELD_NAME); IFeatureCursor inserts = null; IFeatureBuffer buffer = null; try { object missing = Type.Missing; ISpatialReference spatialReference = ((IGeoDataset)outputFeatureClass).SpatialReference; inserts = outputFeatureClass.Insert(false); buffer = outputFeatureClass.CreateFeatureBuffer(); List<Cell> cells = bv.Cells; message.AddMessage(string.Format("{0} cells calculated", cells.Count)); List<Edge> edges = bv.Edges; message.AddMessage(string.Format("{0} edges calculated", edges.Count)); List<Vertex> vertices = bv.Vertices; message.AddMessage(string.Format("{0} vertexes calculated", vertices.Count)); stepPro.Message = "Write cells"; stepPro.MaxRange = 0; stepPro.MaxRange = cells.Count; stepPro.Show(); for (int cellIndex = 0; cellIndex < cells.Count; cellIndex++) { try { if(cellIndex % 5000 == 0) message.AddMessage(String.Format("{0}. {1} cells processed.", DateTime.Now, cellIndex)); Cell cell = cells[cellIndex]; int currentSite = cell.Site; IGeometryCollection geometryCollection = new GeometryBagClass() { SpatialReference = spatialReference }; //ignores any sliver cells if (cell.IsOpen || cell.EdgesIndex.Count < 3) continue; ISegmentCollection segmentCollection = createSegments(cell, bv, method, spatialReference); if (((IArea)segmentCollection).Area <= 0) { message.AddMessage("A invalid geometry has been detected, try reversing the orientation."); ISegmentCollection reversed_segmentCollection = new PolygonClass() { SpatialReference = spatialReference }; for (int i = segmentCollection.SegmentCount - 1; i >= 0; i--) { ISegment segment = (ISegment)segmentCollection.get_Segment(i); segment.ReverseOrientation(); reversed_segmentCollection.AddSegment(segment); } segmentCollection = reversed_segmentCollection; } ((IPolygon)segmentCollection).SpatialReference = spatialReference; if (((IArea)segmentCollection).Area <= 0) { message.AddWarning("An empty shell has been created"); for (int i = 0; i < segmentCollection.SegmentCount; i++) { ISegment segment = (ISegment)segmentCollection.get_Segment(i); message.AddMessage(String.Format("From {0}, {1} To {2},{3}", segment.FromPoint.X, segment.FromPoint.Y, segment.ToPoint.X, segment.ToPoint.Y)); } } //set attributes site_key sk = (currentSite >= point_sites.Count) ? segment_sites[currentSite - point_sites.Count] : point_sites[currentSite]; if (!sk.isEmpty) { buffer.set_Value(featureSourceIndx, input_featureClasses[sk.featureClassIndex].featureclass.AliasName); buffer.set_Value(featureIDIndx, sk.objectID); } else { buffer.set_Value(featureSourceIndx, DBNull.Value); buffer.set_Value(featureIDIndx, DBNull.Value); } IPolygon voronoiPolygon = (IPolygon)segmentCollection; buffer.Shape = (IPolygon)voronoiPolygon; inserts.InsertFeature(buffer); } catch (Exception e) { message.AddWarning("Failed to create a cell"); } } } finally { if (buffer != null) Marshal.ReleaseComObject(buffer); if (inserts != null) Marshal.ReleaseComObject(inserts); } GPHelperFunctions.createSpatialIndex(outputFeatureClass); } catch (Exception exx) { message.AddError(2, exx.Message); message.AddMessage(exx.ToString()); } finally { if (outputFeatureClass != null) Marshal.ReleaseComObject(outputFeatureClass); ((IProgressor)trackcancel).Hide(); } }
public bool HasTangentCurveMatchFeatures(IFeatureClass FeatureClass, IPolycurve inPolycurve, string WhereClause, double AngleToleranceTangentCompareInDegrees, double StraightLinesBreakLessThanInDegrees, double MaximumDeltaInDegrees, double ExcludeTangentsShorterThan, out int outFoundTangentCurvesCount, ref List<string> CurveInfoFromNeighbours) { outFoundTangentCurvesCount = 0; ILine pOriginalChord = new Line(); pOriginalChord.PutCoords(inPolycurve.FromPoint, inPolycurve.ToPoint); IVector3D vecOriginalSelected = new Vector3DClass(); vecOriginalSelected.PolarSet(pOriginalChord.Angle, 0, 1); int idxRadius = FeatureClass.FindField("RADIUS"); if (idxRadius == -1) return false; int idxCenterPointID = FeatureClass.FindField("CENTERPOINTID"); if (idxCenterPointID == -1) return false; object val = null; IGeometryBag pGeomBag = new GeometryBagClass(); IGeometryCollection pGeomColl = (IGeometryCollection)pGeomBag; IGeometry MultiPartPolyLine = new PolylineClass(); //qi IGeoDataset pGeoDS = (IGeoDataset)FeatureClass; ISpatialReference spatialRef = pGeoDS.SpatialReference; MultiPartPolyLine.SpatialReference = spatialRef; IGeometryCollection geometryCollection2 = MultiPartPolyLine as IGeometryCollection; ILine pTangentLineAtEnd = new Line(); //new ILine pTangentLineAtStart = new Line(); //new object objMissing = Type.Missing; for (int i = 0; i < 2; i++) { ILine pThisLine = null; if (i == 0) { inPolycurve.QueryTangent(esriSegmentExtension.esriExtendAtTo, 1.0, true, 0.2, pTangentLineAtEnd); pThisLine = new Line(); pThisLine.PutCoords(pTangentLineAtEnd.FromPoint, pTangentLineAtEnd.ToPoint); pGeomColl.AddGeometry(pThisLine); } else { inPolycurve.QueryTangent(esriSegmentExtension.esriExtendAtFrom, 0.0, true, 0.2, pTangentLineAtStart); pThisLine = new Line(); pThisLine.PutCoords(pTangentLineAtStart.FromPoint, pTangentLineAtStart.ToPoint); pGeomColl.AddGeometry(pThisLine); } //Create a new path for each line. ISegmentCollection newPath = new PathClass(); newPath.AddSegment((ISegment)pThisLine, ref objMissing, ref objMissing); //The spatial reference associated with geometryCollection will be assigned to all incoming paths and segments. geometryCollection2.AddGeometry(newPath as IGeometry, ref objMissing, ref objMissing); } //now buffer the lines IGeometryCollection outBufferedGeometryCol = new GeometryBagClass(); for (int jj = 0; jj < geometryCollection2.GeometryCount; jj++) { IPath pPath = geometryCollection2.get_Geometry(jj) as IPath; IGeometryCollection pPolyL = new PolylineClass(); pPolyL.AddGeometry((IGeometry)pPath); ITopologicalOperator topologicalOperator = (ITopologicalOperator)pPolyL; IPolygon pBuffer = topologicalOperator.Buffer(0.1) as IPolygon; outBufferedGeometryCol.AddGeometry(pBuffer, ref objMissing, ref objMissing); } ITopologicalOperator pUnionedBuffers = null; pUnionedBuffers = new PolygonClass() as ITopologicalOperator; pUnionedBuffers.ConstructUnion((IEnumGeometry)outBufferedGeometryCol); ISpatialFilter pSpatFilt = new SpatialFilter(); pSpatFilt.WhereClause = WhereClause; pSpatFilt.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; pSpatFilt.SearchOrder = esriSearchOrder.esriSearchOrderSpatial; pSpatFilt.Geometry = (IGeometry)pUnionedBuffers; IFeatureCursor pFeatCursLines = null; try { pFeatCursLines = FeatureClass.Search(pSpatFilt, false); } catch (Exception ex) { MessageBox.Show(ex.Message); return false; } IVector3D vecFoundGeom = new Vector3DClass(); IFeature pFeat = pFeatCursLines.NextFeature(); bool bHasTangentStraightLineAtJunction = false; List<int> lstLargeBreak = new List<int>(); while (pFeat != null) { IGeometry pFoundLineGeom = pFeat.ShapeCopy; IPolycurve pFoundLineAsPolyCurve = pFoundLineGeom as IPolycurve; int iRelativeOrientation = GetRelativeOrientation(pFoundLineAsPolyCurve, inPolycurve); //iRelativeOrientation == 1 --> closest points are original TO and found TO //iRelativeOrientation == 2 --> closest points are original TO and found FROM //iRelativeOrientation == 3 --> closest points are original FROM and found TO //iRelativeOrientation == 4 --> closest points are original FROM and found FROM //if the feature has no radius attribute, skip. double dRadius = 0; int iCtrPoint = -1; val = pFeat.get_Value(idxRadius); if (val == DBNull.Value) dRadius = 0; else dRadius = (double)val; val = pFeat.get_Value(idxCenterPointID); IPolycurve pPolyCurve = pFoundLineGeom as IPolycurve; ILine pFoundChordCandidate = new LineClass(); pFoundChordCandidate.PutCoords(pPolyCurve.FromPoint, pPolyCurve.ToPoint); //first check for liklihood that subject line is supposed to stay straight, by //geometry chord bearing angle break test vecFoundGeom.PolarSet(pFoundChordCandidate.Angle, 0, 1); double dDotProd = vecFoundGeom.DotProduct(vecOriginalSelected); double dAngleCheck = Math.Acos(dDotProd) * 180 / Math.PI; //in degrees dAngleCheck = Math.Abs(dAngleCheck); double dLargeAngleBreakInDegrees = 3; if (dAngleCheck > dLargeAngleBreakInDegrees && dAngleCheck < (180 - dLargeAngleBreakInDegrees)) //large angle break non-tangent, greater than 3 degrees { if (!lstLargeBreak.Contains(iRelativeOrientation)) lstLargeBreak.Add(iRelativeOrientation); } if ((dAngleCheck <= StraightLinesBreakLessThanInDegrees || (180 - dAngleCheck) < StraightLinesBreakLessThanInDegrees) && val == DBNull.Value && dRadius == 0 && !(pPolyCurve.Length< ExcludeTangentsShorterThan)) { if (lstLargeBreak.Contains(iRelativeOrientation)) bHasTangentStraightLineAtJunction = true; } if (val == DBNull.Value || dRadius == 0 || pPolyCurve.Length< ExcludeTangentsShorterThan) {//if the feature has a null centrpointID then skip. Marshal.ReleaseComObject(pFeat); pFeat = pFeatCursLines.NextFeature(); continue; } if (Math.Abs(inPolycurve.Length / dRadius * 180 / Math.PI) > MaximumDeltaInDegrees) { //if the resulting curve would have a central angle more than MaximumDeltaInDegrees degrees then skip Marshal.ReleaseComObject(pFeat); pFeat = pFeatCursLines.NextFeature(); continue; } iCtrPoint = (int)val; //if geometry of curve neighbour curves have been cracked then there can be more than one segment //however since all segments would be circular arcs, just need to test the first segment ISegmentCollection pFoundLineGeomSegs = pFoundLineGeom as ISegmentCollection; ISegment pSeg = pFoundLineGeomSegs.get_Segment(0); if (!(pSeg is ICircularArc)) { Marshal.ReleaseComObject(pFeat); pFeat = pFeatCursLines.NextFeature(); continue; } dRadius = (double)pFeat.get_Value(idxRadius); IVector3D vect1 = new Vector3DClass(); IVector3D vect2 = new Vector3DClass(); ILine tang = new Line(); double dUnitSignChange = 1; if (iRelativeOrientation == 1) //closest points are original TO and found TO { dUnitSignChange = -1; vect1.PolarSet(pTangentLineAtEnd.Angle, 0, 1); pFoundLineAsPolyCurve.QueryTangent(esriSegmentExtension.esriExtendAtTo, 1.0, true, 1, tang); vect2.PolarSet(tang.Angle, 0, 1); } else if (iRelativeOrientation == 2)//closest points are original TO and found FROM { vect1.PolarSet(pTangentLineAtEnd.Angle, 0, 1); pFoundLineAsPolyCurve.QueryTangent(esriSegmentExtension.esriExtendAtFrom, 0.0, true, 1, tang); vect2.PolarSet(tang.Angle, 0, 1); } else if (iRelativeOrientation == 3)//closest points are original FROM and found TO { vect1.PolarSet(pTangentLineAtStart.Angle, 0, 1); pFoundLineAsPolyCurve.QueryTangent(esriSegmentExtension.esriExtendAtTo, 1.0, true, 1, tang); vect2.PolarSet(tang.Angle, 0, 1); } else if (iRelativeOrientation == 4)//closest points are original FROM and found FROM { dUnitSignChange = -1; vect1.PolarSet(pTangentLineAtStart.Angle, 0, 1); pFoundLineAsPolyCurve.QueryTangent(esriSegmentExtension.esriExtendAtFrom, 0.0, true, 1, tang); vect2.PolarSet(tang.Angle, 0, 1); } dDotProd = vect1.DotProduct(vect2); dAngleCheck = Math.Acos(dDotProd) * 180 / Math.PI; //in degrees dAngleCheck = Math.Abs(dAngleCheck); if (dAngleCheck < AngleToleranceTangentCompareInDegrees || (180 - dAngleCheck) < AngleToleranceTangentCompareInDegrees) { double dDerivedRadius = dRadius * dUnitSignChange; string sHarvestedCurveInfo = pFeat.OID.ToString() + "," + dDerivedRadius.ToString("#.000") + "," + iCtrPoint.ToString() + "," + "t"; CurveInfoFromNeighbours.Add(sHarvestedCurveInfo); outFoundTangentCurvesCount++; } Marshal.ReleaseComObject(pFeat); pFeat = pFeatCursLines.NextFeature(); } Marshal.FinalReleaseComObject(pFeatCursLines); if (bHasTangentStraightLineAtJunction) return false; //open to logic change to be less conservative bool bHasParallelCurveFeaturesNearby = (outFoundTangentCurvesCount > 0); return bHasParallelCurveFeaturesNearby; }
public static IGeometry get_GraphicShape(IEnumElement theElements, int a_Dimensionality, bool multipart) { IGeometry theReturn = null; IGeometryCollection theGeomColl = null; object missing = Type.Missing; if (theElements != null) { theElements.Reset(); IElement theElement = theElements.Next(); while (theElement != null) { if (theGeomColl == null) theGeomColl = new GeometryBagClass(); IGeometry theShape = null; if (theElement is IGroupElement) { theShape = get_GraphicShape(((IGroupElement)theElement).Elements, a_Dimensionality, multipart); } else if (theElement is ICircleElement || theElement is IPolygonElement || theElement is IRectangleElement || theElement is IEllipseElement || theElement is ILineElement || theElement is IMarkerElement) theShape = theElement.Geometry; if (theShape != null) theGeomColl.AddGeometry(theShape, ref missing, ref missing); theElement = theElements.Next(); } } if (theGeomColl != null && theGeomColl.GeometryCount > 0) { ITopologicalOperator theTopoOp = null; switch (a_Dimensionality) { case 0: if (multipart) { theTopoOp = new MultipointClass(); theTopoOp.ConstructUnion((IEnumGeometry)theGeomColl); } else theTopoOp = theGeomColl.get_Geometry(0) as ITopologicalOperator; break; case 1: theTopoOp = new PolylineClass(); theTopoOp.ConstructUnion((IEnumGeometry)theGeomColl); break; case 2: theTopoOp = new PolygonClass(); theTopoOp.ConstructUnion((IEnumGeometry)theGeomColl); break; } theReturn = theTopoOp as IGeometry; } return theReturn; }
private void createGrapicAndZoomTo(string capakeyResponse, datacontract.geojson Geom) { IRgbColor inClr = new RgbColorClass() { Red = 0, Blue = 100, Green = 0 }; ; IRgbColor outLine = new RgbColorClass() { Red = 0, Blue = 200, Green = 0, Transparency = 240 }; if (Geom.type == "MultiPolygon") { datacontract.geojsonMultiPolygon muniPolygons = JsonConvert.DeserializeObject<datacontract.geojsonMultiPolygon>(capakeyResponse); IGeometryCollection multiPoly = new GeometryBagClass(); clearGraphics(); foreach (datacontract.geojsonPolygon poly in muniPolygons.toPolygonList()) { IPolygon lbPoly = geopuntHelper.geojson2esriPolygon(poly, (int)dataHandler.CRS.Lambert72); lbPoly.SimplifyPreserveFromTo(); IGeometry prjGeom = geopuntHelper.Transform((IGeometry)lbPoly, map.SpatialReference); IElement muniGrapic = geopuntHelper.AddGraphicToMap(map, prjGeom, inClr, outLine, 2, true); graphics.Add(muniGrapic); multiPoly.AddGeometry(prjGeom); } view.Extent = ((IGeometryBag)multiPoly).Envelope; view.Refresh(); } else if (Geom.type == "Polygon") { datacontract.geojsonPolygon municipalityPolygon = JsonConvert.DeserializeObject<datacontract.geojsonPolygon>(capakeyResponse); IPolygon lbPoly = geopuntHelper.geojson2esriPolygon(municipalityPolygon, (int)dataHandler.CRS.Lambert72); lbPoly.SimplifyPreserveFromTo(); IPolygon prjPoly = (IPolygon)geopuntHelper.Transform((IGeometry)lbPoly, map.SpatialReference); view.Extent = prjPoly.Envelope; clearGraphics(); IElement muniGrapic = geopuntHelper.AddGraphicToMap(map, (IGeometry)prjPoly, inClr, outLine, 3, true); graphics.Add(muniGrapic); view.Refresh(); } }
public static IGeometry GetSearchGeometryFromGraphics(IGraphicsContainer graphics) { IGeometryCollection geometryBag = new GeometryBagClass(); IElement element; IGeometry geometry; graphics.Reset(); element = graphics.Next(); object before = Type.Missing; object after = Type.Missing; while (element != null) { geometry = element.Geometry; if (geometry is IPolygon) geometryBag.AddGeometry(geometry, ref before, ref after); element = graphics.Next(); } IGeometry searchGeometry = geometryBag as IGeometry; return searchGeometry; }
/// <summary> /// 合并元素 /// </summary> /// <param name="pMap">当前操作地图</param> /// <param name="layer">当前操作图层</param> private void union(IMap pMap,ILayer layer) { IFeatureLayer pFeatureLayer = layer as IFeatureLayer; IDataset pDataset = pFeatureLayer.FeatureClass as IDataset; IWorkspaceEdit pWorkspaceEdit = pDataset.Workspace as IWorkspaceEdit; pWorkspaceEdit.StartEditOperation(); IEnumFeature pEnumFeature = pMap.FeatureSelection as IEnumFeature; IFeature allFeature = pEnumFeature.Next(); IFeatureCursor pEF = pFeatureLayer.Search(null, false); IFeature pFeature = pEF.NextFeature(); IGeometry pGeometry = pFeature.Shape; IGeometryCollection pGeometrybag=new GeometryBagClass(); object oMissing = Type.Missing; while (allFeature != null) { IGeometry mGeometry = allFeature.Shape as IGeometry; pGeometrybag.AddGeometry(mGeometry, ref oMissing, ref oMissing); allFeature.Delete(); allFeature = pEnumFeature.Next(); } ITopologicalOperator2 pTopOperator = (ITopologicalOperator2)pGeometry; IEnumGeometry pEnumGeometry = pGeometrybag as IEnumGeometry; pTopOperator.ConstructUnion(pEnumGeometry); pFeature.Shape = pGeometry; pFeature.Store(); pWorkspaceEdit.StopEditOperation(); }
public IGeometry createGeometry(IFeatureClass ftrCls) { IGeometry geometryBag = new GeometryBagClass(); geometryBag.SpatialReference = ((IGeoDataset)ftrCls).SpatialReference; IGeometryCollection geoCol = (IGeometryCollection)geometryBag; IFeatureCursor fCur = ftrCls.Search(null, false); IFeature ftr = fCur.NextFeature(); object objB = Type.Missing; object objA = Type.Missing; while (ftr != null) { IGeometry geo = ftr.Shape; geoCol.AddGeometry(geo, ref objB, ref objA); ftr = fCur.NextFeature(); } return (IGeometry)geoCol; }
private List<IElement> CreateElementAois(List<IPolygon> polygons, out IEnvelope encompassingEnvelope) { var rgbColor = new RgbColorClass { Red = 0, Green = 0, Blue = 255, Transparency = 200 }; var geometryBag = new GeometryBagClass(); geometryBag.SpatialReference = ArcMap.Document.FocusMap.SpatialReference; IGeometryCollection geometryCollection = geometryBag; var elements = new List<IElement>(); foreach (var polygon in polygons) { geometryCollection.AddGeometry(polygon); IElement element = null; // Polygon elements ILineSymbol lineSymbol = new SimpleLineSymbolClass(); lineSymbol.Color = rgbColor; lineSymbol.Width = 2.0; ISimpleFillSymbol simpleFillSymbol = new SimpleFillSymbolClass(); simpleFillSymbol.Color = rgbColor; simpleFillSymbol.Style = esriSimpleFillStyle.esriSFSNull; simpleFillSymbol.Outline = lineSymbol; IFillShapeElement fillShapeElement = new PolygonElementClass(); fillShapeElement.Symbol = simpleFillSymbol; element = (IElement)fillShapeElement; // Explicit Cast element.Geometry = polygon; elements.Add(element); } // Create the polygon that will be the union of the features returned from the search cursor. // The spatial reference of this feature does not need to be set ahead of time. The // ConstructUnion method defines the constructed polygon's spatial reference to be the same as // the input geometry bag. ITopologicalOperator unionedPolygon = new PolygonClass(); unionedPolygon.ConstructUnion(geometryBag); var masterPoly = (IPolygon)unionedPolygon; encompassingEnvelope = masterPoly.Envelope; return elements; }
private byte[] GetSpeciesExtentHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = "{\"Content-Type\" : \"text/javascript\"}"; long? idnoValue; //out parameter for the ID_NO as a long operationInput.TryGetAsLong("ID_NO", out idnoValue); //get the ID_NO parameter IQueryFilter queryFilter = new QueryFilterClass(); //instantiate a filter for the passed species queryFilter.WhereClause = "ID_NO='" + idnoValue + "' AND Legend<>''"; //set the where clause IFeatureCursor featureCursor = speciesFeatureClass.Search(queryFilter, false); //get the feature cursor to the matching features IFeature feature = null; //for iterating through the features IGeometryCollection pGeometryCollection = new GeometryBagClass() as IGeometryCollection; //instantiate a geometry bag to get the extent object obj = Type.Missing; //needed to add geometries to the geometry bag while ((feature = featureCursor.NextFeature()) != null) //iterate through the matching features and add the geometries to the geometry bag { pGeometryCollection.AddGeometry(feature.ShapeCopy, ref obj, ref obj); //add the geometry } JsonObject result = new JsonObject(); //create the return json object IEnvelope extent = (pGeometryCollection as IGeometry).Envelope; //get the extent of the geometry bag JsonObject jsonExtent = Conversion.ToJsonObject(extent); //convert the extent to json //TODO: Set the spatial reference for the extent in the SOE - at the moment it is set in the client code result.AddObject("extent", jsonExtent); //write the extent to the result object result.AddString("featureCount", pGeometryCollection.GeometryCount.ToString()); //get the number of features return Encoding.UTF8.GetBytes(result.ToJson()); //return the json }
public static IGeometryCollection ConstructTrianglesOutline(IGeometry trianglesGeometry) { IGeometryCollection outlineGeometryCollection = new GeometryBagClass(); IPointCollection trianglesPointCollection = trianglesGeometry as IPointCollection; // Triangles: an unlinked set of triangles, where every three vertices completes a new triangle. if ((trianglesPointCollection.PointCount % 3) != 0) { throw new Exception("Triangles Geometry Point Count Must Be Divisible By 3. " + trianglesPointCollection.PointCount); } else { for (int i = 0; i < trianglesPointCollection.PointCount; i+=3) { IPointCollection outlinePointCollection = new PolylineClass(); outlinePointCollection.AddPoint(trianglesPointCollection.get_Point(i), ref _missing, ref _missing); outlinePointCollection.AddPoint(trianglesPointCollection.get_Point(i + 1), ref _missing, ref _missing); outlinePointCollection.AddPoint(trianglesPointCollection.get_Point(i + 2), ref _missing, ref _missing); outlinePointCollection.AddPoint(trianglesPointCollection.get_Point(i), ref _missing, ref _missing); //Simulate: Polygon.Close IGeometry outlineGeometry = outlinePointCollection as IGeometry; MakeZAware(outlineGeometry); outlineGeometryCollection.AddGeometry(outlineGeometry, ref _missing, ref _missing); } } return outlineGeometryCollection; }
private void btnOK_Click(object sender, EventArgs e) { int startWaypoint = Convert.ToInt16(this.txtStartOID.Text);//OID of the waypoint from where waypoint renaming will begin int startKmPost = Convert.ToInt16(this.txtStartKMPost.Text); //The first km post will be one greater than this number. int startKmOID = Convert.ToInt16(this.txtStartKMOID.Text); //The objectID of the km post we are starting from. 0 if it doesn't exist. Note that the DistanceAlongTrail here should probably match startKmPost variable above. //Example: "887:1866,888"... A comma delimited list of OIDS of trails that from previous section to include in this section when building km points. //The first OID (887) is followed by a colon and the OID of the connected waypoint in the direction we are going. This then gets the needed partial geometry. string extraSegmentsOIDSFromLastSectionToUseAsGeometryForKMPosts = Convert.ToString(this.txtExtra.Text);// "407:1170"; // "887:1866,888"; //string endWaypoint = "'139'"; string section = "'" + Convert.ToString(this.txtSection.Text) + "'"; string trailName = "'" + Convert.ToString(this.txtTrailName.Text) + "'"; string kmPostPrefix = "K" + trailName.Replace("'", "") + ":"; if (trailName == "'GDT'") { kmPostPrefix = "K"; } IGeometryCollection geomCol = new GeometryBagClass(); IFeatureClass trailFC = null; IFeatureClass waypointFC = null; GetFeatureClasses(ref trailFC, ref waypointFC); IWorkspaceEdit wse = (IWorkspaceEdit)(waypointFC as IDataset).Workspace; wse.StartEditing(false); wse.StartEditOperation(); try { IQueryFilter qf = new QueryFilterClass(); IFeatureCursor feCur = null; qf.WhereClause = "NAME = " + trailName + " and SECTIONNAME = " + section; feCur = trailFC.Search(qf, false); IFeature trailFe = feCur.NextFeature(); Type factoryType = Type.GetTypeFromProgID("esriGeometry.SpatialReferenceEnvironment"); System.Object obj = Activator.CreateInstance(factoryType); ISpatialReferenceFactory spatialReferenceFactory = obj as ISpatialReferenceFactory; ISpatialReference sf = spatialReferenceFactory.CreateGeographicCoordinateSystem(4326); double totalDistance = 0; List<IFeature> segmentsMatchingNameAndSection = new List<IFeature>(); double totalSegments = 0; double totalCosValues = 0; //used so that we can get the average cosine value needed to split the unioned polyline later in the code. while (trailFe != null) { totalSegments++; geomCol.AddGeometry(trailFe.ShapeCopy); IPoint startPoint = (trailFe.ShapeCopy as IPointCollection).get_Point(0); startPoint.Project(sf); double cos = Math.Cos(startPoint.Y / 57.2958); totalCosValues += cos; double segLen = (((IPolyline)trailFe.ShapeCopy).Length * cos) / 1000.0; totalDistance += segLen; //segLen =Math.Round( segLen,2) ; trailFe.set_Value(trailFe.Fields.FindField("SEGMENTLENGTH"), segLen); trailFe.Store(); segmentsMatchingNameAndSection.Add(trailFe); trailFe = feCur.NextFeature(); } //Next waypoint contains a key as a waypoint, then the next downstream trail and waypoint. Dictionary<IFeature, List<IFeature>> nextWaypoint = new Dictionary<IFeature, List<IFeature>>(); IFeature startWaypointFe = null; foreach (IFeature trailFe2 in segmentsMatchingNameAndSection) { trailFe2.set_Value(trailFe2.Fields.FindField("TRAILLENGTH"), Math.Round(totalDistance, 2)); IPoint fromPoint = ((IPolyline)trailFe2.ShapeCopy).FromPoint; IPoint toPoint = ((IPolyline)trailFe2.ShapeCopy).ToPoint; List<IPoint> fromToPoint = new List<IPoint> { fromPoint, toPoint }; string prefix = "From"; IFeatureCursor connectedWPCursor = null; IFeature fromWaypointFeature = null; foreach (IPoint pnt in fromToPoint) { ISpatialFilter spatfilter = new SpatialFilterClass(); spatfilter.Geometry = pnt; spatfilter.GeometryField = "SHAPE"; spatfilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIndexIntersects; connectedWPCursor = waypointFC.Search(spatfilter, false); IFeature waypointFeature = connectedWPCursor.NextFeature(); trailFe2.set_Value(trailFe2.Fields.FindField(prefix + "Waypoint"), waypointFeature.OID); if (prefix == "From") { fromWaypointFeature = waypointFeature; string wpName = "'" + fromWaypointFeature.get_Value(fromWaypointFeature.Fields.FindField("NAME")).ToString() + "'"; int wpOID = fromWaypointFeature.OID; if (wpOID == startWaypoint) { startWaypointFe = fromWaypointFeature; } } else { nextWaypoint.Add(fromWaypointFeature, new List<IFeature> { trailFe2, waypointFeature }); } prefix = "To"; } trailFe2.Store(); Marshal.FinalReleaseComObject(connectedWPCursor); } Marshal.FinalReleaseComObject(feCur); int totalDecimetersForTrail = Convert.ToInt16(totalDistance * 10); IFeature wayPointOnTrail = startWaypointFe; double runningLength = 0; HashSet<string> usedDisplayNames = new HashSet<string>(); while (wayPointOnTrail != null) { wayPointOnTrail.set_Value(wayPointOnTrail.Fields.FindField("decimetersAlongTrail"), runningLength); int decimetersRemainingOnTrail = totalDecimetersForTrail - Convert.ToInt32(Math.Round(runningLength, 0)); wayPointOnTrail.set_Value(wayPointOnTrail.Fields.FindField("decimetersToEnd"), decimetersRemainingOnTrail); string displayName = section.Replace("'", "") + decimetersRemainingOnTrail.ToString(); if (trailName != "'GDT'") { displayName = trailName.Replace("'", "") + ":" + decimetersRemainingOnTrail.ToString(); } while (usedDisplayNames.Contains(displayName)) { displayName += "."; } usedDisplayNames.Add(displayName); wayPointOnTrail.set_Value(wayPointOnTrail.Fields.FindField("DisplayName"), displayName); if (nextWaypoint.ContainsKey(wayPointOnTrail)) { IFeature connectedTrailFeature = nextWaypoint[wayPointOnTrail][0]; double segmentLength = Convert.ToDouble(connectedTrailFeature.get_Value(connectedTrailFeature.Fields.FindField("SEGMENTLENGTH")));//In km segmentLength = segmentLength * 10; runningLength += segmentLength;// Convert.ToInt16(segmentLength); wayPointOnTrail.Store(); wayPointOnTrail = nextWaypoint[wayPointOnTrail][1]; } else { break; } } //Make the kilometer posts. //The geometries in geomCol won't include the last segment(s) from the previous section (if applicable). Here we need to add them in. //In the comma delimited list extraSegmentsOIDSFromLastSectionToUseAsGeometryForKMPosts (example: "887:1866,888"), the first segment is a partial geometry //that connects to another waypoint which is specified after the colon. All subsequent OIDS (e.g. 888) use the full geometry. string[] extraOIDS = extraSegmentsOIDSFromLastSectionToUseAsGeometryForKMPosts.Split(','); if (extraOIDS[0] != "") { foreach (string oidWaypointPair in extraOIDS) { string[] geomString = oidWaypointPair.Split(':'); string oid = geomString[0]; string waypointOID = ""; if (geomString.Length > 1) { waypointOID = geomString[1]; } IFeature trailFromPrevSection = trailFC.GetFeature(Convert.ToInt32(oid)); if (waypointOID == "") { geomCol.AddGeometry(trailFromPrevSection.ShapeCopy); } else { IFeature startKMPost = waypointFC.GetFeature(startKmOID); IPoint startKMPoint = startKMPost.ShapeCopy as IPoint; IPoint endPointOnFirstLine = waypointFC.GetFeature(Convert.ToInt32(waypointOID)).ShapeCopy as IPoint; ICurve curve = trailFromPrevSection.ShapeCopy as ICurve; bool brs = true; double dfc = 0; double dacToKMPoint = -1; double dacToWayPointOnPath = -1; IPoint outStartPoint = new PointClass(); curve.QueryPointAndDistance(esriSegmentExtension.esriNoExtension, startKMPoint, false, outStartPoint, ref dacToKMPoint, ref dfc, ref brs); curve.QueryPointAndDistance(esriSegmentExtension.esriNoExtension, endPointOnFirstLine, false, outStartPoint, ref dacToWayPointOnPath, ref dfc, ref brs); ICurve outCurve = new PolylineClass(); double fromDistance = dacToKMPoint; double toDistance = dacToWayPointOnPath; if (dacToWayPointOnPath < dacToKMPoint) { fromDistance = dacToWayPointOnPath; toDistance = dacToKMPoint; } curve.GetSubcurve(fromDistance, toDistance, false, out outCurve); geomCol.AddGeometry(outCurve); } } } //Total segments is the number of segments in the section, but does NOT include all the segments that might be used to build the km post. double averageCosineValue = 1.0 / (totalCosValues / totalSegments); ITopologicalOperator unionedPolyline = new PolylineClass(); unionedPolyline.ConstructUnion(geomCol as IEnumGeometry); IPolyline fullTrail = unionedPolyline as IPolyline; IPoint fromPoint2 = fullTrail.FromPoint; IPoint toPoint2 = fullTrail.ToPoint; List<IPoint> endPoints = new List<IPoint>() { fromPoint2, toPoint2 }; foreach (IPoint pnt in endPoints) { ISpatialFilter spatFilter = new SpatialFilterClass(); spatFilter.Geometry = pnt; spatFilter.GeometryField = "SHAPE"; spatFilter.WhereClause = "OBJECTID = " + startKmOID; spatFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; feCur = waypointFC.Search(spatFilter, false); IFeature wayPointFe = feCur.NextFeature(); if (wayPointFe != null) { if (wayPointFe.OID != startKmOID) { //The from point of the unioned polyline doesn't match, so we have to reverse direction. fullTrail.ReverseOrientation(); } int splitIndex = 1; int kmAlongTrail = startKmPost; while (true) { double splitDistance = splitIndex * 1000 * averageCosineValue; if (splitDistance > fullTrail.Length) { break; } IPoint outPoint = new PointClass(); fullTrail.QueryPoint(esriSegmentExtension.esriNoExtension, splitDistance, false, outPoint); IFeature newWaypointFe = null; bool kmPostExistsAlready = false; IQueryFilter existsQF = new QueryFilterClass(); kmAlongTrail += 1; existsQF.WhereClause = "NAME = '" + kmPostPrefix + kmAlongTrail.ToString() + "'"; IFeatureCursor kmExistsCursor = waypointFC.Search(existsQF, false); try { IFeature kmExistsFe = kmExistsCursor.NextFeature(); if(kmExistsFe != null) { kmPostExistsAlready = true; newWaypointFe = kmExistsFe; } if (kmPostExistsAlready == false) { newWaypointFe= waypointFC.CreateFeature(); } newWaypointFe.Shape = outPoint; newWaypointFe.set_Value(newWaypointFe.Fields.FindField("SUBTYPE"), 1); newWaypointFe.set_Value(newWaypointFe.Fields.FindField("kmAlongTrail"), kmAlongTrail); string desc = trailName.Replace("'", "") + ":" + section.Replace("'", ""); newWaypointFe.set_Value(newWaypointFe.Fields.FindField("Description"), desc); if (kmAlongTrail % 5 == 0) { newWaypointFe.set_Value(newWaypointFe.Fields.FindField("display"), 1); } else { newWaypointFe.set_Value(newWaypointFe.Fields.FindField("display"), 0); } newWaypointFe.set_Value(newWaypointFe.Fields.FindField("NAME"), kmPostPrefix + kmAlongTrail.ToString()); newWaypointFe.Store(); splitIndex++; } finally { Marshal.FinalReleaseComObject(kmExistsCursor); } } break; //we created km post, so there is not a need to inspect the other end of the polyline } else { //could happen if the end point of the polyline isn't the point we are looking for } } } catch (Exception ex) { } wse.StopEditOperation(); wse.StopEditing(true); }
//上朔追踪查找管线涉及的地块 public static void UpStreamFindParcels(MainFrm pMainFrm, IEnumNetEID pEnumResultEdges, IGeometricNetwork pGeoNetwork) { try { AxMapControl axMap = pMainFrm.getMapControl(); IFeatureLayer pFeatLayerSewerLines = FindFeatLayer("Sewer Lines", pMainFrm); IFeatureLayer pFeatLayerParcels = FindFeatLayer("Parcels", pMainFrm); //从所选择的Sewer线特征中创建几何包 IGeometryCollection pGeomBag = new GeometryBagClass(); object missing = Type.Missing; int lEID; int iUserClassID; int iUserID; int iUserSubID; INetElements pNetElements = pGeoNetwork.Network as INetElements; pEnumResultEdges.Reset(); IFeature pFeature; for (int j = 0; j <= pEnumResultEdges.Count - 1; j++) { lEID = pEnumResultEdges.Next(); pNetElements.QueryIDs(lEID, esriElementType.esriETEdge, out iUserClassID, out iUserID, out iUserSubID); pFeature = pFeatLayerSewerLines.FeatureClass.GetFeature(iUserID); pGeomBag.AddGeometry(pFeature.Shape, ref missing, ref missing); // MessageBox.Show(iUserClassID.ToString()+","+iUserID.ToString()+","+iUserSubID.ToString()); } //进行空间拓扑叠加操作以用于查找地块信息 ISpatialFilter pSpatialFilter = new SpatialFilterClass(); pSpatialFilter.Geometry = pGeomBag as IGeometry ; pSpatialFilter.GeometryField = "Shape"; pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; pSpatialFilter.SearchOrder = esriSearchOrder.esriSearchOrderSpatial; //获得交叉到的地块信息 IFeatureCursor pFeatCursor=pFeatLayerParcels.FeatureClass.Search(pSpatialFilter, false); //增加被选择的地块数据到地图的图形图层数据中 ICompositeGraphicsLayer pComGraphicLayer = new CompositeGraphicsLayerClass(); ILayer pLayer = pComGraphicLayer as ILayer ; pLayer.Name = "受影响的地块"; IGraphicsContainer pGraphicContainer = pComGraphicLayer as IGraphicsContainer; //增加所选择的地块到图形容器中 ISimpleFillSymbol pSymFill=new SimpleFillSymbolClass(); IFillSymbol pFillSymbol=pSymFill as IFillSymbol; IRgbColor pRgbColor=new RgbColorClass(); pRgbColor.Red=0; pRgbColor.Green=200; pRgbColor.Blue=100; pFillSymbol.Color=pRgbColor as IColor; ICartographicLineSymbol pCartoLine=new CartographicLineSymbolClass(); IRgbColor pRgbColor2=new RgbColorClass(); pRgbColor2.Red=100; pRgbColor2.Green=200; pRgbColor2.Blue=100; pCartoLine.Width=2; pCartoLine.Color =pRgbColor2 as IColor; pFillSymbol.Outline=pCartoLine; //创建存放所有地块特征的数组 IArray pFeatArray = new ArrayClass(); pFeature=pFeatCursor.NextFeature(); while (pFeature != null) { IElement pPolyElement = new PolygonElementClass(); IFillShapeElement pFillShapeElement = pPolyElement as IFillShapeElement; pPolyElement.Geometry = pFeature.Shape; pFillShapeElement.Symbol = pFillSymbol; pGraphicContainer.AddElement(pPolyElement, 0); pFeatArray.Add(pFeature); pFeature = pFeatCursor.NextFeature(); } axMap.AddLayer(pGraphicContainer as ILayer); axMap.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics,null,null); frmUpstreamCreateOwnerList frmUpstreamCreateOwnerList1 = new frmUpstreamCreateOwnerList(pMainFrm,pFeatLayerParcels, pFeatArray); frmUpstreamCreateOwnerList1.Show(); } catch (Exception eX) { MessageBox.Show(eX.Message); } }
public static IGeometry WMerge(this IGeometry Sgeometry,IGeometry geometry) { IGeometryCollection geometryCollection = new GeometryBagClass(); geometryCollection.AddGeometry(Sgeometry); geometryCollection.AddGeometry(geometry); ITopologicalOperator unionedpolygon = new PolygonClass(); unionedpolygon.ConstructUnion(geometryCollection as IEnumGeometry); return unionedpolygon as IGeometry; }