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(); }
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> /// 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> /// 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); }
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 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(); } }
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); }
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 }); } }
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 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 LearningTestBufferConstructionHandlingSingleEmptyGeometry() { var inputBag = new GeometryBagClass(); inputBag.AddGeometry(new PolygonClass()); IBufferConstruction bufferConstruction = GetBufferConstruction(); IGeometryBag outputBag = new GeometryBagClass(); bufferConstruction.ConstructBuffers(inputBag, 10, (IGeometryCollection)outputBag); Assert.AreEqual(0, ((IGeometryCollection)outputBag).GeometryCount); }
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 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); } }
private void CreateGraph() { IClone pClone; IFeature pFeature; IGeometryCollection pGeometryBag; esriGeometryType GeoType; pGeometryBag = new GeometryBagClass(); for (int i = 0; i < m_OriginFeatureArray.Count; i++) { pFeature = (IFeature)m_OriginFeatureArray.get_Element(i); GeoType = pFeature.Shape.GeometryType; if (GeoType == esriGeometryType.esriGeometryPolygon || GeoType == esriGeometryType.esriGeometryPolyline) { object a = System.Reflection.Missing.Value; object b = System.Reflection.Missing.Value; pClone = (IClone)pFeature.Shape; pGeometryBag.AddGeometry((IGeometry)pClone.Clone(), ref a, ref b); } } if (bBegineMove) { if (m_pGraph != null) { m_pGraph.SetEmpty(); } m_pCursor = null; } IEnumGeometry pEnumGeometry = (IEnumGeometry)pGeometryBag; m_pGraph.Load(pEnumGeometry, false, true); bBegineMove = false; }
public IGeometry GetSpatialFilter() { IGeometry geom = null; IFeature feature; IFeatureCursor featCursor = null; IQueryFilter queryFilter = new QueryFilter(); queryFilter.WhereClause = tbQuery.Text; //set query clause //query DataOperator dataOperator = new DataOperator(m_map); IFeatureLayer featureLayer = (IFeatureLayer)dataOperator.GetLayerByName(cbLayerName.Text); try { //get feature cursor featCursor = (IFeatureCursor)featureLayer.FeatureClass.Search(queryFilter, false); } catch { MessageBox.Show("Invalid query!"); return(null); } feature = featCursor.NextFeature(); IFeatureClass featureClass = feature.Class as IFeatureClass; //combine the geometries int count = 0; IGeometryCollection geometries = new GeometryBagClass(); object missing = Type.Missing; while (feature != null) { geom = feature.ShapeCopy; geometries.AddGeometry(geom, ref missing, ref missing); feature = featCursor.NextFeature(); count++; } //combine the geometries if (count > 1) { ITopologicalOperator unionedGeometry = null; switch (featureClass.ShapeType) { case esriGeometryType.esriGeometryMultipoint: unionedGeometry = new MultipointClass(); break; case esriGeometryType.esriGeometryPolyline: unionedGeometry = new PolylineClass(); break; case esriGeometryType.esriGeometryPolygon: unionedGeometry = new PolygonClass(); break; case esriGeometryType.esriGeometryPoint: unionedGeometry = new MultipointClass(); break; default: break; } unionedGeometry.ConstructUnion(geometries as IEnumGeometry); geom = unionedGeometry as IGeometry; } //get buffer if (cbMethod.Text == "Are within a distance of") { ITopologicalOperator ipTO = (ITopologicalOperator)geom; IGeometry iGeomBuffer = ipTO.Buffer(int.Parse(tbSearchDistance.Text)); geom = iGeomBuffer; } return(geom); }
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(); }
/// <summary> /// 合并多条多义线,如果合并的多义线不是简单的多义线则抛出异常 /// </summary> /// <param name="pPolylines">多义线集</param> /// <returns>多义线</returns> public static IPolyline UnionPolylines(IPolyline[] pPolylines) { // 第一条线段 int indexFirst = -1; int degree = 0; IRelationalOperator pRO = null; int nSelected = pPolylines.Length; IPolyline pRetPolyline = new PolylineClass(); ITopologicalOperator pTopoOper = (ITopologicalOperator)pRetPolyline; IGeometryCollection pGeometryCollection = new GeometryBagClass(); for (int i = 0; i < pPolylines.Length; i++) { object o = Type.Missing; pGeometryCollection.AddGeometry(pPolylines[i], ref o, ref o); } pTopoOper.ConstructUnion((IEnumGeometry)pGeometryCollection); IGeometryCollection pGeometryColl = (IGeometryCollection)pTopoOper; if (pGeometryColl.GeometryCount > 1) { throw new Exception("线段的空间连接不正确"); } return((IPolyline)pTopoOper); // AddGeometry // 数据检查 //ConstructUnion /* * double tol = GeometryHelper.ConvertPixelsToMapUnits(pActiveView, 4); * IPoint pHitPoint = null; * double hitDist = 0; * int partIndex = 0; * int vertexIndex = 0; * int vertexOffset = 0; * bool vertex = false; * if (EditHelper.HitTest(tol, _pMenuPosition, pFeature, ref pHitPoint, ref hitDist, ref partIndex, ref vertexIndex, ref vertexOffset, ref vertex)) * { * * } */ for (int i = 0; i < nSelected; i++) { int nTouch = 0; pRO = (IRelationalOperator)pPolylines[i]; IHitTest hittest = (IHitTest)pRO; for (int j = 0; j < nSelected; j++) { if (i != j && pRO.Touches(pPolylines[j])) { nTouch++; } } if (nTouch == 0 || nTouch > 2) { throw new Exception("line touch error"); } else if (nTouch == 1) { if (indexFirst == -1) { indexFirst = i; } if (++degree > 2) { throw new Exception("multi patchs"); } } } // 依据第一条线topo有序 if (indexFirst == -1) { throw new Exception("line circle"); } IPolyline pTemp = pPolylines[indexFirst]; pPolylines[indexFirst] = pPolylines[0]; pPolylines[0] = pTemp; IPolyline pPolyline = new PolylineClass(); ISegmentCollection pSegments = (ISegmentCollection)pPolyline; pSegments.AddSegmentCollection((ISegmentCollection)pPolylines[0]); for (int i = 0; i < nSelected - 1; i++) { pRO = (IRelationalOperator)pPolylines[i]; for (int j = i + 1; j < nSelected; j++) { if (pRO.Touches(pPolylines[j])) { pTemp = pPolylines[j]; pPolylines[j] = pPolylines[i + 1]; pPolylines[i + 1] = pTemp; if (IdentialPoint(pPolylines[i].FromPoint, pPolylines[i + 1].ToPoint)) { //pSegments.AddSegmentCollection(); } break; } } } return(null); }
private IGeometryCollection CreateBufferPolygons() { IGeometryCollection geometries = new GeometryBagClass() as IGeometryCollection; if (queryFeatureClass == null) { return(null); } double bufferDistance = 0; if (Information.IsNumeric(txtDistance.Text)) { bufferDistance = Convert.ToDouble(txtDistance.Text); } else { return(null); } IFeatureCursor featureCursor = queryFeatureClass.Search(null, false); IFeature feature = featureCursor.NextFeature(); while (feature != null) { IGeometry geometry = feature.ShapeCopy; ITopologicalOperator topogeometry = geometry as ITopologicalOperator; if (topogeometry == null || geometry == null) { return(null); } object obj = Type.Missing; IGeometry bufferResult; if (queryFeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon) { IPolygon4 polygon = geometry as IPolygon4; IGeometry buffBoundaryExtAndInt; ITopologicalOperator topoBuffer; #region "switch (polygonBufferType)" switch (polygonBufferType) { case "多边形边界内外缓冲": //多边形边界内外缓冲即对多边形的所有内外环边界进行缓冲,要注意各边界缓冲区的合并 buffBoundaryExtAndInt = BufferExtAndIntBoundary(polygon, bufferDistance, true); geometries.AddGeometry(buffBoundaryExtAndInt, ref obj, ref obj); break; case "多边形边界外缓冲": //多边形边界外缓冲即对多边形的所有内外环边界仅作外缓冲 //可以由普通多边形缓冲减去多边形本身得到 IGeometry bufferPolygon = topogeometry.Buffer(bufferDistance); topoBuffer = bufferPolygon as ITopologicalOperator; bufferResult = topoBuffer.Difference(geometry); DrawGraphics(bufferResult); geometries.AddGeometry(bufferResult, ref obj, ref obj); break; case "多边形边界内缓冲": //多边形边界内缓冲即对多边形的所有内外环边界仅作内缓冲 //可以由多边形边界内外缓冲和多边形本身求交得到 buffBoundaryExtAndInt = BufferExtAndIntBoundary(polygon, bufferDistance, false); topoBuffer = buffBoundaryExtAndInt as ITopologicalOperator; bufferResult = topoBuffer.Intersect(geometry, esriGeometryDimension.esriGeometry2Dimension); DrawGraphics(bufferResult); geometries.AddGeometry(bufferResult, ref obj, ref obj); break; case "多边形内缓冲": //普通多边形缓冲就是在多边形外作缓冲, 多边形内缓冲即对多边形向内作缓冲 //可以通过给负距离产生 topoBuffer = geometry as ITopologicalOperator; bufferResult = topoBuffer.Buffer(-bufferDistance); DrawGraphics(bufferResult); geometries.AddGeometry(bufferResult, ref obj, ref obj); break; case "普通多边形缓冲": topoBuffer = geometry as ITopologicalOperator; bufferResult = topoBuffer.Buffer(bufferDistance); DrawGraphics(bufferResult); geometries.AddGeometry(bufferResult, ref obj, ref obj); break; default: break; } #endregion } else { bufferResult = topogeometry.Buffer(bufferDistance); DrawGraphics(bufferResult); geometries.AddGeometry(bufferResult, ref obj, ref obj); } feature = featureCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(featureCursor); ITopologicalOperator topoGeometries = geometries as ITopologicalOperator; topoGeometries.Simplify(); return(geometries); }
private void btnApply_Click(object sender, EventArgs e) { try { Verify(); string strQuery; strQuery = this.txtExpress.Text; if (strQuery == "") { return; } ILayer pLayer; pLayer = ClsSelectQuery.FunFindFeatureLayerByName(cboLayerList.Text, ClsDeclare.g_pMap); if (pLayer == null) { return; } IFeatureLayer pFeatLayer; pFeatLayer = pLayer as IFeatureLayer; if (pFeatLayer.Visible == false) { } //ClsDeclare.g_ErrorHandler.DisplayInformation("请选择可见图层",false,"确定",null); IFeatureSelection pFeatureSelection; pFeatureSelection = pFeatLayer as IFeatureSelection; IQueryFilter pQueryFilter = new QueryFilterClass(); pQueryFilter.WhereClause = strQuery; esriSelectionResultEnum SelType; SelType = esriSelectionResultEnum.esriSelectionResultNew; switch (this.cboSelectMethod.Text) { case "创建一个新的选择结果": { if (ClsDeclare.g_pMap.SelectionCount > 0) { ClsDeclare.g_pMap.ClearSelection(); } SelType = esriSelectionResultEnum.esriSelectionResultNew; } break; case "添加到当前选择集中": SelType = esriSelectionResultEnum.esriSelectionResultAdd; break; case "从当前选择结果中移除": SelType = esriSelectionResultEnum.esriSelectionResultSubtract; break; case "从当前选择结果中选择": SelType = esriSelectionResultEnum.esriSelectionResultAnd; break; } if (pFeatLayer.Selectable) { pFeatureSelection.SelectFeatures(pQueryFilter, SelType, false); } IActiveView pActiveView; pActiveView = ClsDeclare.g_pMap as IActiveView; pActiveView.Refresh(); IFeatureClass pFeatCls; IGeometryCollection pGeometryCol; IGeometryBag pGeometryBag; IEnumIDs pEnumIDs; IFeature pFeature; int iOBJID; pGeometryCol = new GeometryBagClass(); pGeometryBag = pGeometryCol as IGeometryBag; pFeatCls = pFeatLayer.FeatureClass; pEnumIDs = pFeatureSelection.SelectionSet.IDs; iOBJID = pEnumIDs.Next(); object Missing = Type.Missing; object Missing1 = Type.Missing; while (iOBJID != -1) { pFeature = pFeatCls.GetFeature(iOBJID); pGeometryCol.AddGeometry(pFeature.Shape, ref Missing, ref Missing1); iOBJID = pEnumIDs.Next(); } IHookActions pHookActions; IHookHelper pHookHelper; pHookHelper = new HookHelperClass(); pHookHelper.Hook = ClsDeclare.g_Sys.MapControl.Object; pHookActions = pHookHelper as IHookActions; if (pHookActions.get_ActionSupported(pGeometryBag.Envelope, esriHookActions.esriHookActionsPan)) { pHookActions.DoAction(pGeometryBag.Envelope, esriHookActions.esriHookActionsPan); } Application.DoEvents(); } catch (Exception ex) { MessageBox.Show("错误", ex.StackTrace, MessageBoxButtons.OK, MessageBoxIcon.Error); //ClsDeclare.g_ErrorHandler.HandleError(true,null,0,null,ex.StackTrace); throw; } }
private void UnionFeatures(IEnumFeature selectedFeatures) { IFeature feature = null; IGeometry geometry = null; object missing = Type.Missing; selectedFeatures.Reset(); feature = selectedFeatures.Next(); if (feature == null) { return; } IFeatureClass featureClass = feature.Class as IFeatureClass; IGeometryCollection geometries = new GeometryBagClass(); while (feature != null) { geometry = feature.ShapeCopy; geometries.AddGeometry(geometry, ref missing, ref missing); feature = selectedFeatures.Next(); } ITopologicalOperator unionedGeometry = null; switch (featureClass.ShapeType) { case esriGeometryType.esriGeometryMultipoint: unionedGeometry = new MultipointClass(); break; case esriGeometryType.esriGeometryPolyline: unionedGeometry = new PolylineClass(); break; case esriGeometryType.esriGeometryPolygon: unionedGeometry = new PolygonClass(); break; default: break; } unionedGeometry.ConstructUnion(geometries as IEnumGeometry); ITopologicalOperator2 topo = unionedGeometry as ITopologicalOperator2; topo.IsKnownSimple_2 = false; topo.Simplify(); IFeatureClass targetFeatureClass = currentLayer.FeatureClass; IDataset dataset = featureClass as IDataset; IWorkspaceEdit workspaceEdit = dataset.Workspace as IWorkspaceEdit; if (!(workspaceEdit.IsBeingEdited())) { return; } try { workspaceEdit.StartEditOperation(); IFeature unionedFeature = targetFeatureClass.CreateFeature(); unionedFeature.Shape = unionedGeometry as IGeometry; unionedFeature.Store(); workspaceEdit.StopEditOperation(); } catch (Exception ex) { workspaceEdit.AbortEditOperation(); MessageBox.Show("要素合并失败!!" + ex.Message, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
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; }
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 }
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 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 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; } }
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; }
/// <summary> /// 空间定位 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnApply_Click(object sender, EventArgs e) { String uSource = string.Empty; List <ILayer> list = new List <ILayer>(); try { //Verify(); if (ClsDeclare.g_pMap.LayerCount <= 0) { MessageBox.Show("图层控件中没有图层,请添加图层!"); return; } string strQuery; strQuery = this.txtExpress.Text; if (strQuery == "") { return; } Collection <IRow> collect = new Collection <IRow>(); int i = 0, j = 0; try { //FrmItemAttr frmItemAttr = new FrmItemAttr(); if (this.txtExpress.Text == "") { //ClsDeclare.g_ErrorHandler.DisplayInformation("请选择查询表达式", false, "确定", null); return; } if (relationTable != null) { for (i = 0; i < relationTable.Fields.FieldCount; i++) { //string test1 = relationTable.Fields.get_Field(i).Name.ToString(); //string test2 = SubstrField(this.lstField.Text.Trim()); if (relationTable.Fields.get_Field(i).Name.ToString().Trim() == SubstrField(this.lstField.Text.Trim())) { ICursor pCursor; pCursor = relationTable.Search(null, false); IRow pRow; pRow = pCursor.NextRow(); while (pRow != null) { string test = this.lstValue.SelectedItem.ToString().Replace("'", ""); string test3 = pRow.get_Value(i).ToString(); if (pRow.get_Value(i).ToString() == this.lstValue.SelectedItem.ToString().Replace("'", "")) { collect.Add(pRow); } pRow = pCursor.NextRow(); } } } } //for (j = 0; j < collect.Count; j++) //{ // frmItemAttr.LoadData(collect[j]); //} //frmItemAttr.Show(); //break; } catch (Exception) { //ClsDeclare.g_ErrorHandler.DisplayInformation("可能表达式有误,请先验证表达式", false, "确定",null); //throw; MessageBoxEx.Show("可能表达式有误,请先验证表达式"); } if (collect.Count > 0) { for (j = 0; j < collect.Count; j++) { IRow ptempRow = collect[j]; uSource = ptempRow.get_Value(ptempRow.Fields.FindField("ESOURCE")).ToString(); list = GetLayers(uSource); } } for (int k = 0; k < list.Count; k++) { ILayer pLayer; //pLayer = ClsSelectQuery.FunFindFeatureLayerByName(cboLayerList.Text, ClsDeclare.g_pMap); pLayer = list[k]; if (pLayer == null) { return; } IFeatureLayer pFeatLayer; pFeatLayer = pLayer as IFeatureLayer; //if (pFeatLayer.Visible == false) //{ //} //ClsDeclare.g_ErrorHandler.DisplayInformation("请选择可见图层",false,"确定",null); IFeatureSelection pFeatureSelection; pFeatureSelection = pFeatLayer as IFeatureSelection; IQueryFilter pQueryFilter = new QueryFilterClass(); pQueryFilter.WhereClause = strQuery; esriSelectionResultEnum SelType; SelType = esriSelectionResultEnum.esriSelectionResultNew; switch (this.cboSelectMethod.Text) { case "创建一个新的选择结果": { if (ClsDeclare.g_pMap.SelectionCount > 0) { ClsDeclare.g_pMap.ClearSelection(); } SelType = esriSelectionResultEnum.esriSelectionResultNew; } break; case "添加到当前选择集中": SelType = esriSelectionResultEnum.esriSelectionResultAdd; break; case "从当前选择结果中移除": SelType = esriSelectionResultEnum.esriSelectionResultSubtract; break; case "从当前选择结果中选择": SelType = esriSelectionResultEnum.esriSelectionResultAnd; break; } if (pFeatLayer.Selectable) { pFeatureSelection.SelectFeatures(pQueryFilter, SelType, false); } IActiveView pActiveView; pActiveView = ClsDeclare.g_pMap as IActiveView; pActiveView.Refresh(); IFeatureClass pFeatCls; IGeometryCollection pGeometryCol; IGeometryBag pGeometryBag; IEnumIDs pEnumIDs; IFeature pFeature; int iOBJID; pGeometryCol = new GeometryBagClass(); pGeometryBag = pGeometryCol as IGeometryBag; pFeatCls = pFeatLayer.FeatureClass; pEnumIDs = pFeatureSelection.SelectionSet.IDs; iOBJID = pEnumIDs.Next(); object Missing = Type.Missing; object Missing1 = Type.Missing; while (iOBJID != -1) { pFeature = pFeatCls.GetFeature(iOBJID); pGeometryCol.AddGeometry(pFeature.Shape, ref Missing, ref Missing1); iOBJID = pEnumIDs.Next(); } IHookActions pHookActions; IHookHelper pHookHelper; pHookHelper = new HookHelperClass(); pHookHelper.Hook = ClsDeclare.g_Sys.MapControl.Object; pHookActions = pHookHelper as IHookActions; if (pHookActions.get_ActionSupported(pGeometryBag.Envelope, esriHookActions.esriHookActionsPan)) { pHookActions.DoAction(pGeometryBag.Envelope, esriHookActions.esriHookActionsPan); } Application.DoEvents(); } } catch (Exception ex) { //MessageBox.Show("错误", ex.StackTrace, MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("表达式错误", ex.StackTrace, MessageBoxButtons.OK, MessageBoxIcon.Error); //ClsDeclare.g_ErrorHandler.HandleError(true,null,0,null,ex.StackTrace); throw; } }
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(); }
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 void OnDblClick() { Editor.UniqueInstance.CheckOverlap = false; try { IFeatureLayer targetLayer = Editor.UniqueInstance.TargetLayer; object missing = Type.Missing; if (!this.m_IsUsed || (this.m_LineFeedback == null)) { return; } if (this.m_Step > 1) { IPolyline polyline = this.m_LineFeedback.Stop(); if (polyline == null) { this.Init(); return; } IFeatureClass featureClass = targetLayer.FeatureClass; if (featureClass == null) { this.Init(); return; } IGeoDataset dataset = featureClass as IGeoDataset; if (polyline.SpatialReference != dataset.SpatialReference) { polyline.Project(dataset.SpatialReference); polyline.SpatialReference = dataset.SpatialReference; } IGeometry inGeometry = polyline; GeometryBagClass lineSrc = new GeometryBagClass(); lineSrc.AddGeometry(inGeometry, ref missing, ref missing); targetLayer.Selectable = true; IDataset dataset2 = featureClass as IDataset; IWorkspace selectionWorkspace = dataset2.Workspace; IEnvelope extent = dataset.Extent; IInvalidArea invalidArea = new InvalidAreaClass(); IFeatureConstruction construction = new FeatureConstructionClass(); IFeatureSelection selection = targetLayer as IFeatureSelection; ISelectionSet selectionSet = selection.SelectionSet; Editor.UniqueInstance.SetArea = false; Editor.UniqueInstance.StartEditOperation(); ISpatialReferenceTolerance spatialReference = (ISpatialReferenceTolerance)dataset.SpatialReference; construction.AutoCompleteFromGeometries(featureClass, extent, lineSrc, invalidArea, spatialReference.XYTolerance, selectionWorkspace, out selectionSet); if ((selectionSet == null) || (selectionSet.Count < 1)) { Editor.UniqueInstance.AbortEditOperation(); } else { List <IFeature> pFeatureList = new List <IFeature>(); IEnumIDs iDs = selectionSet.IDs; iDs.Reset(); for (int i = iDs.Next(); i >= 0; i = iDs.Next()) { IFeature pFeature = featureClass.GetFeature(i); FeatureFuncs.SetFeatureArea(pFeature); pFeatureList.Add(pFeature); } if (selectionSet.Count == 1) { IFeature feature = pFeatureList[0]; selection.Clear(); selection.Add(feature); AttributeManager.AttributeAddHandleClass.AttributeAdd(ref feature); } else { AttributeManager.AttributeSplitHandleClass.AttributeSplit(null, ref pFeatureList); } Editor.UniqueInstance.StopEditOperation("AutoComplete"); } Editor.UniqueInstance.SetArea = true; this.m_hookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection | esriViewDrawPhase.esriViewGeography, null, this.m_hookHelper.ActiveView.Extent); } } catch (Exception exception) { this.mErrOpt.ErrorOperate(this.mSubSysName, "ShapeEdit.AutoComplete", "OnDblClick", exception.GetHashCode().ToString(), exception.Source, exception.Message, "", "", ""); } this.Init(); Editor.UniqueInstance.CheckOverlap = true; }
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 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(); }
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; }
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; }
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; }
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(); } }
//合并要素 private void UnionFeatures(IEnumFeature selectedFeatures, IFeature pMergeFeature) { IFeature feature = null; IGeometry geometry = null; object missing = Type.Missing; selectedFeatures.Reset(); feature = selectedFeatures.Next(); if (feature == null) { return; } IFeatureClass featureClass = feature.Class as IFeatureClass; IGeometryCollection geometries = new GeometryBagClass(); IDataset dataset = null; while (feature != null) { geometry = feature.ShapeCopy; geometries.AddGeometry(geometry, ref missing, ref missing); feature = selectedFeatures.Next(); } ITopologicalOperator2 unionedGeometry = null; switch (featureClass.ShapeType) { case esriGeometryType.esriGeometryMultipoint: unionedGeometry = new MultipointClass(); break; case esriGeometryType.esriGeometryPolyline: unionedGeometry = new PolylineClass(); break; case esriGeometryType.esriGeometryPolygon: unionedGeometry = new PolygonClass(); break; default: break; } IEnumGeometry enuGeo = geometries as IEnumGeometry; unionedGeometry.ConstructUnion(enuGeo); ITopologicalOperator2 topo = unionedGeometry as ITopologicalOperator2; topo.IsKnownSimple_2 = false; topo.Simplify(); IFeatureClass targetFeatureClass = currentLayer.FeatureClass; dataset = featureClass as IDataset; selectedFeatures.Reset(); //如果没有IWorkspaceEdit则无法进行撤销重做操作 IWorkspaceEdit workspaceEdit = dataset.Workspace as IWorkspaceEdit; try { //workspaceEdit.StartEditOperation(); IFeature unionedFeature = targetFeatureClass.CreateFeature(); IFields pFields = unionedFeature.Fields; IFieldsEdit pFieldsEdit = pFields as IFieldsEdit; IField pField = null; for (int i = 0; i < pFields.FieldCount; i++) { pField = pFields.Field[i]; if (targetFeatureClass.AreaField != null && targetFeatureClass.LengthField != null) { if (pField.Name != targetFeatureClass.OIDFieldName && pField.Name != targetFeatureClass.ShapeFieldName && pField.Name != targetFeatureClass.AreaField.Name && pField.Name != targetFeatureClass.LengthField.Name) { unionedFeature.set_Value(i, pMergeFeature.Value[i]); } } else { if (pField.Name != targetFeatureClass.OIDFieldName && pField.Name != targetFeatureClass.ShapeFieldName) { unionedFeature.set_Value(i, pMergeFeature.Value[i]); } } } unionedFeature.Shape = unionedGeometry as IGeometry; unionedFeature.Store(); while ((feature = selectedFeatures.Next()) != null) { feature.Delete(); } workspaceEdit.StopEditOperation(); } catch (Exception ex) { //SysLogHelper.WriteOperationLog("要素合并错误", ex.Source, "数据编辑"); MessageBox.Show(ex.Message); } }
//��˷�ٲ��ҹ����漰�ĵؿ� 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); } }
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; }
private IGeometry method_2() { double x = 0.0; double y = 0.0; double xMax = 0.0; double yMax = 0.0; IPoint inPoint = null; IPoint point2 = null; IPoint point3 = null; IPoint point4 = null; IPointCollection points = null; IGeometry geometry = new RingClass(); object missing = System.Type.Missing; IFeatureWorkspace workspace = null; IFeatureClass class2 = null; IFeatureCursor cursor = null; IFeature feature = null; IGeometryCollection geometrys = new GeometryBagClass(); IGeometryBag bag = geometrys as IGeometryBag; workspace = null; try { if (workspace == null) { return(geometry); } class2 = workspace.OpenFeatureClass("TKMC"); if (class2 == null) { return(geometry); } cursor = class2.Search(null, false); for (feature = cursor.NextFeature(); feature != null; feature = cursor.NextFeature()) { if (!feature.Shape.IsEmpty) { geometrys.AddGeometry(feature.ShapeCopy, ref missing, ref missing); } } if (geometrys.GeometryCount >= 1) { inPoint = new PointClass(); point2 = new PointClass(); point3 = new PointClass(); point4 = new PointClass(); x = bag.Envelope.XMin; y = bag.Envelope.YMin; xMax = bag.Envelope.XMax; yMax = bag.Envelope.YMax; inPoint.PutCoords(x, yMax); point2.PutCoords(xMax, yMax); point3.PutCoords(xMax, y); point4.PutCoords(x, y); points = (IPointCollection)geometry; points.AddPoint(inPoint, ref missing, ref missing); points.AddPoint(point2, ref missing, ref missing); points.AddPoint(point3, ref missing, ref missing); points.AddPoint(point4, ref missing, ref missing); points.AddPoint(inPoint, ref missing, ref missing); } } catch (Exception exception) { Debug.WriteLine(exception.Message); } return(geometry); }
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> /// 合并元素 /// </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 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 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); }
//上朔追踪查找管线涉及的地块 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); } }