private static IGeometryCollection ClipGeometryCollection(IGeometryCollection geom, Envelope clipEnv) { var clipPoly = geom.Factory.ToGeometry(clipEnv); var clipped = new List<IGeometry>(); for (var i = 0; i < geom.NumGeometries; i++) { var g = geom.GetGeometryN(i); IGeometry result = null; // don't clip unless necessary if (clipEnv.Contains(g.EnvelopeInternal)) result = g; else if (clipEnv.Intersects(g.EnvelopeInternal)) { result = clipPoly.Intersection(g); // keep vertex key info result.UserData = g.UserData; } if (result != null && !result.IsEmpty) { clipped.Add(result); } } return geom.Factory.CreateGeometryCollection(GeometryFactory.ToGeometryArray(clipped)); }
private static void WriteShape(IGeometryCollection geometries, string shapepath) { if (File.Exists(shapepath)) File.Delete(shapepath); var sfw = new ShapefileWriter(geometries.Factory); sfw.Write(Path.GetFileNameWithoutExtension(shapepath), geometries); }
/// <summary> /// Constructs an iterator over the given <c>GeometryCollection</c>. /// </summary> /// <param name="parent"> /// The collection over which to iterate; also, the first /// element returned by the iterator. /// </param> public GeometryCollectionEnumerator(IGeometryCollection parent) { this.parent = parent; atStart = true; index = 0; max = parent.NumGeometries; }
/// <summary> /// Constructs an iterator over the given <c>GeometryCollection</c>. /// </summary> /// <param name="parent"> /// The collection over which to iterate; also, the first /// element returned by the iterator. /// </param> public GeometryCollectionEnumerator(IGeometryCollection parent) { _parent = parent; _atStart = true; _index = 0; _max = parent.NumGeometries; }
private static IEnumerable<IGeometry> DoMerge(IGeometryCollection coll) { if (coll == null) throw new ArgumentNullException("coll"); IEnumerable<IGeometry> items = GetItems(coll); yield return UnaryUnionOp.Union(items.ToArray()); }
public void LoadSourceGeometries(IGeometryCollection geomColl) { for (int i = 0; i < geomColl.NumGeometries; i++) { IGeometry geom = geomColl.GetGeometryN(i); LoadVertices(geom.Coordinates, geom.UserData); } }
public static void AddOutlineToGraphicsLayer3D(IGraphicsContainer3D graphicsContainer3D, IGeometryCollection geometryCollection, IColor color, esriSimple3DLineStyle style, double width) { for (int i = 0; i < geometryCollection.GeometryCount; i++) { IGeometry geometry = geometryCollection.get_Geometry(i); graphicsContainer3D.AddElement(ElementUtilities.ConstructPolylineElement(geometry, color, style, width)); } }
/// <summary> /// Uses the passed geometry collection to generate a QuickGraph. /// </summary> /// <param name="edges"></param> /// <param name="src"></param> /// <param name="dst"></param> public ILineString TestGraphBuilder2WithSampleGeometries(IGeometryCollection edges, ICoordinate src, ICoordinate dst) { GraphBuilder2 builder = new GraphBuilder2(true); foreach (IMultiLineString edge in edges.Geometries) foreach (ILineString line in edge.Geometries) builder.Add(line); builder.Initialize(); return builder.Perform(src, dst); }
/// <summary> /// /// </summary> /// <param name="gc"></param> /// <returns></returns> private bool HasRepeatedPoint(IGeometryCollection gc) { for (int i = 0; i < gc.NumGeometries; i++) { IGeometry g = gc.GetGeometryN(i); if (HasRepeatedPoint(g)) return true; } return false; }
/// <summary> /// Transforms a <see cref="IGeometryCollection" /> object. /// </summary> /// <param name="factory">The factory to create the new <see cref="IGeometryCollection"/></param> /// <param name="geoms">The input <see cref="IGeometryCollection"/></param> /// <param name="transform">The <see cref="IMathTransform"/></param> /// <returns>A transformed <see cref="IGeometryCollection"/></returns> public static IGeometryCollection TransformGeometryCollection(IGeometryFactory factory, IGeometryCollection geoms, IMathTransform transform) { var geometries = geoms.Geometries; var coll = new List<IGeometry>(geometries.Length); foreach (var g in geometries) { var item = TransformGeometry(factory, g, transform); coll.Add(item); } return factory.CreateGeometryCollection(coll.ToArray()); }
/// <summary> /// /// </summary> /// <param name="gc"></param> /// <returns></returns> public IGeometryCollection Map(IGeometryCollection gc) { IList<IGeometry> mapped = new List<IGeometry>(); for (var i = 0; i < gc.NumGeometries; i++) { var g = _mapOp(gc.GetGeometryN(i)); if (!g.IsEmpty) mapped.Add(g); } return gc.Factory.CreateGeometryCollection( GeometryFactory.ToGeometryArray(mapped)); }
public void SetUp() { IPoint point = factory.CreatePoint(new Coordinate(1, 1)); ILineString linestring = factory.CreateLineString(new[] { new Coordinate(1, 1), new Coordinate(2, 2), new Coordinate(3, 3), }); ILinearRing shell = factory.CreateLinearRing(new[] { new Coordinate(1, 1), new Coordinate(2, 2), new Coordinate(3, 3), new Coordinate(1, 1) }); IPolygon polygon = factory.CreatePolygon(shell); geometries = new IGeometry[] { point, linestring, polygon }; serializedGeometries = "\"geometries\":[{\"type\":\"Point\",\"coordinates\":[1.0,1.0]},{\"type\":\"LineString\",\"coordinates\":[[1.0,1.0],[2.0,2.0],[3.0,3.0]]},{\"type\":\"Polygon\",\"coordinates\":[[[1.0,1.0],[2.0,2.0],[3.0,3.0],[1.0,1.0]]]}]"; collection = factory.CreateGeometryCollection(geometries); serializedCollection = "{\"type\":\"GeometryCollection\",\"geometries\":[{\"type\":\"Point\",\"coordinates\":[1.0,1.0]},{\"type\":\"LineString\",\"coordinates\":[[1.0,1.0],[2.0,2.0],[3.0,3.0]]},{\"type\":\"Polygon\",\"coordinates\":[[[1.0,1.0],[2.0,2.0],[3.0,3.0],[1.0,1.0]]]}]}"; }
private static IEnumerable<IGeometry> DoClean(IGeometryCollection coll) { if (coll == null) throw new ArgumentNullException("coll"); IEnumerable<IGeometry> items = GetItems(coll); foreach (IGeometry geom in items) { DouglasPeuckerSimplifier simplifier = new DouglasPeuckerSimplifier(geom); IGeometry clean = simplifier.GetResultGeometry(); yield return clean; } }
public List<string> ParseGeometryCollection(IGeometryCollection geometryCollection) { var coords = new List<string>(); //for each geometry in the collection for (int i = 0; i < geometryCollection.GeometryCount; i++) { var pGeom = geometryCollection.Geometry[i]; var pntCollection = (IPointCollection)pGeom; for (var a = 0; a < pntCollection.PointCount; a++) { var roundedPoint = Math.Round(pntCollection.Point[a].Y, 5) + " " + Math.Round(pntCollection.Point[a].X, 5); //compare the point to the last one entered to make sure only unique points are entered string lastPoint = ""; if (coords.Count > 1) lastPoint = coords[coords.Count - 1]; if (!lastPoint.Equals(roundedPoint)) coords.Add(roundedPoint); } } return coords; }
/// <summary> /// Writes a shapefile to disk. /// </summary> /// <remarks> /// Assumes the type given for the first geometry is the same for all subsequent geometries. /// For example, is, if the first Geometry is a Multi-polygon/ Polygon, the subsequent geometies are /// Muli-polygon/ polygon and not lines or points. /// The dbase file for the corresponding shapefile contains one column called row. It contains /// the row number. /// </remarks> /// <param name="filename">The filename to write to (minus the .shp extension).</param> /// <param name="geometryCollection">The GeometryCollection to write.</param> public void Write(string filename, IGeometryCollection geometryCollection) { System.IO.FileStream shpStream = new System.IO.FileStream(filename + ".shp", System.IO.FileMode.Create); System.IO.FileStream shxStream = new System.IO.FileStream(filename + ".shx", System.IO.FileMode.Create); BigEndianBinaryWriter shpBinaryWriter = new BigEndianBinaryWriter(shpStream); BigEndianBinaryWriter shxBinaryWriter = new BigEndianBinaryWriter(shxStream); // assumes ShapeHandler handler = Shapefile.GetShapeHandler(Shapefile.GetShapeType(geometryCollection.Geometries[0])); IGeometry body; int numShapes = geometryCollection.NumGeometries; // calc the length of the shp file, so it can put in the header. int shpLength = 50; for (int i = 0; i < numShapes; i++) { body = (IGeometry) geometryCollection.Geometries[i]; shpLength += 4; // length of header in WORDS shpLength += handler.GetLength(body); // length of shape in WORDS } int shxLength = 50 + (4*numShapes); // write the .shp header ShapefileHeader shpHeader = new ShapefileHeader(); shpHeader.FileLength = shpLength; // get envelope in external coordinates IEnvelope env = geometryCollection.EnvelopeInternal; IEnvelope bounds = ShapeHandler.GetEnvelopeExternal(geometryFactory.PrecisionModel, env); shpHeader.Bounds = bounds; // assumes Geometry type of the first item will the same for all other items // in the collection. shpHeader.ShapeType = Shapefile.GetShapeType(geometryCollection.Geometries[0]); shpHeader.Write(shpBinaryWriter); // write the .shx header ShapefileHeader shxHeader = new ShapefileHeader(); shxHeader.FileLength = shxLength; shxHeader.Bounds = shpHeader.Bounds; // assumes Geometry type of the first item will the same for all other items in the collection. shxHeader.ShapeType = Shapefile.GetShapeType(geometryCollection.Geometries[0]); shxHeader.Write(shxBinaryWriter); // write the individual records. int _pos = 50; // header length in WORDS for (int i = 0; i < numShapes; i++) { body = geometryCollection.Geometries[i]; int recordLength = handler.GetLength(body); shpBinaryWriter.WriteIntBE(i+1); shpBinaryWriter.WriteIntBE(recordLength); shxBinaryWriter.WriteIntBE(_pos); shxBinaryWriter.WriteIntBE(recordLength); _pos += 4; // length of header in WORDS handler.Write(body, shpBinaryWriter, geometryFactory); _pos += recordLength; // length of shape in WORDS } shxBinaryWriter.Flush(); shxBinaryWriter.Close(); shpBinaryWriter.Flush(); shpBinaryWriter.Close(); // WriteDummyDbf(filename + ".dbf", numShapes); }
/// <summary> /// 构造小区立体顶面覆盖网格 /// </summary> /// <param name="cellname"></param> /// <param name="lac"></param> /// <param name="ci"></param> public void constuctCellGrid3Dtops(string cellname, int eNodeB, int ci) { DataTable gridTable = new DataTable(); Hashtable ht = new Hashtable(); ht["eNodeB"] = eNodeB; ht["CI"] = ci; gridTable = IbatisHelper.ExecuteQueryForDataTable("GetSpecifiedCellGrid3Ds", ht); //gridTable = IbatisHelper.ExecuteQueryForDataTable("GetAreaGrid3Ds", null); IDataset dataset = (IDataset)pFeatureLayer.FeatureClass; IWorkspace workspace = dataset.Workspace; //Cast for an IWorkspaceEdit IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace; //start an edit session and operation workspaceEdit.StartEditing(true); workspaceEdit.StartEditOperation(); IFeatureCursor pFeatureCursor = pFeatureClass.Insert(true); IFeatureBuffer pFeatureBuffer; int gxid, gyid, level; double x1, y1, x2, y2, z; double recePower, pathLoss; double gbaseheight = GridHelper.getInstance().getGBaseHeight(); double gheight = GridHelper.getInstance().getGHeight(); //循环添加 foreach (DataRow dataRow in gridTable.Rows) { gxid = int.Parse(dataRow["Gxid"].ToString()); gyid = int.Parse(dataRow["Gyid"].ToString()); level = int.Parse(dataRow["level"].ToString()); Geometric.Point p = GridHelper.getInstance().GridToGeo(gxid, gyid); double lon = p.X; double lat = p.Y; if (!(double.TryParse(dataRow["MinX"].ToString(), out x1) && double.TryParse(dataRow["MinY"].ToString(), out y1) && double.TryParse(dataRow["MaxX"].ToString(), out x2) && double.TryParse(dataRow["MaxY"].ToString(), out y2) && double.TryParse(dataRow["ReceivedPowerdbm"].ToString(), out recePower) && double.TryParse(dataRow["PathLoss"].ToString(), out pathLoss))) { continue; } z = gheight * (level - 1) + gbaseheight; IPoint pointA = GeometryUtilities.ConstructPoint3D(x1, y1, z); IPoint pointB = GeometryUtilities.ConstructPoint3D(x2, y1, z); IPoint pointC = GeometryUtilities.ConstructPoint3D(x2, y2, z); IPoint pointD = GeometryUtilities.ConstructPoint3D(x1, y2, z); IGeometryCollection pGeometryColl = GeometryUtilities.ConstructPolygon(new IPoint[] { pointA, pointB, pointC, pointD }); GeometryUtilities.MakeZAware(pGeometryColl as IGeometry); pFeatureBuffer = pFeatureClass.CreateFeatureBuffer(); pFeatureBuffer.Shape = pGeometryColl as IGeometry; pFeatureBuffer.set_Value(this.GXIDIndex, gxid); pFeatureBuffer.set_Value(this.GYIDIndex, gyid); pFeatureBuffer.set_Value(this.LevelIndex, level); pFeatureBuffer.set_Value(this.eNodeBIndex, eNodeB); pFeatureBuffer.set_Value(this.CIIndex, ci); pFeatureBuffer.set_Value(this.cellNameIndex, cellname); pFeatureBuffer.set_Value(this.LongitudeIndex, lon); pFeatureBuffer.set_Value(this.LatitudeIndex, lat); if (recePower > -41) { pFeatureBuffer.set_Value(this.RecePowerIndex, -41); } //else if (recePower < -110) // pFeatureBuffer.set_Value(this.RecePowerIndex, -110); else { pFeatureBuffer.set_Value(this.RecePowerIndex, recePower); } pFeatureBuffer.set_Value(this.PathLossIndex, pathLoss); pFeatureCursor.InsertFeature(pFeatureBuffer); } //一次性提交 pFeatureCursor.Flush(); //stop editing workspaceEdit.StopEditOperation(); workspaceEdit.StopEditing(true); //IFeatureClassManage pFeatureClassManage = (IFeatureClassManage)pFeatureClass; //pFeatureClassManage.UpdateExtent(); GISMapApplication.Instance.RefreshLayer(pFeatureLayer); //GISMapApplication.Instance.FullExtent(pFeatureLayer.AreaOfInterest); }
public void SplitPolylines() //分割线 { m_pLineFeed = (INewLineFeedback)m_pFeedback; IPolyline pFeatureScissors = (IPolyline)m_pLineFeed.Stop(); //结束绘制切割线 if (pFeatureScissors.Length == 0) { Reset(); return; } ITopologicalOperator pTopologim_CalOperator = (ITopologicalOperator)pFeatureScissors; ILayer pFeatureLayer; pFeatureLayer = m_App.CurrentEditLayer; IGeometry pOldGeometry; IFeature pOldFeature; IWorkspaceEdit pWorkspaceEdit; pWorkspaceEdit = (IWorkspaceEdit)CommonFunction.GetLayerWorkspace(pFeatureLayer); if (pWorkspaceEdit == null) { return; } if (!pWorkspaceEdit.IsBeingEdited()) { return; } pWorkspaceEdit.StartEditOperation(); for (int i = 0; i < m_OriginFeatureArray.Count; i++) //遍历每个选中的要素 { pOldFeature = (IFeature)m_OriginFeatureArray.get_Element(i); pOldGeometry = (IGeometry)pOldFeature.Shape; IArray pArray = new ArrayClass(); //将地理要素的坐标信息添加到点数组中 pArray = CommonFunction.GeometryToArray(pOldGeometry); //跳转到拓扑操作接口,求“剪刀”与选中要素的交点 IGeometry pIntersectGeo = pTopologim_CalOperator.Intersect(pOldGeometry, esriGeometryDimension.esriGeometry0Dimension); if (pIntersectGeo == null) { return; //无交点,则返回 } ITopologicalOperator pTopOp = (ITopologicalOperator)pIntersectGeo; pTopOp.Simplify(); IPointCollection pPointCol = (IPointCollection)pIntersectGeo; //交点的集合 //用相交的点集合打断该线 IPointCollection pTmpPointCol = new MultipointClass(); pTmpPointCol.AddPointCollection(pPointCol); //临时点集 IPolycurve2 pPolyCurve; pPolyCurve = (IPolycurve2)pOldGeometry; //被剪切的线要素 ((ITopologicalOperator)pPolyCurve).Simplify(); IGeometryCollection pGeoCollection; IGeometryCollection pTmpGeoCollection; //保存每次打断产生的线段 pTmpGeoCollection = (IGeometryCollection)pPolyCurve; pGeoCollection = (IGeometryCollection)pPolyCurve; for (int j = 0; j < pPointCol.PointCount; j++) //遍历每个交点 { IPoint pSplitPoint = pPointCol.get_Point(j); int GeoCount = 0; int pGeoCollectionCount = pGeoCollection.GeometryCount; while (GeoCount < pGeoCollectionCount) //遍历每个几何形体 { IPolycurve2 pTmpPolycurve2; pTmpPolycurve2 = CommonFunction.BuildPolyLineFromSegmentCollection((ISegmentCollection)pGeoCollection.get_Geometry(GeoCount)); bool bProject; //是否投影 bool bCreatePart; //是否创建新的附件 bool bSplitted; //分裂是否成功 int lNewPart; int lNewSeg; bProject = true; bCreatePart = true; ((ITopologicalOperator)pTmpPolycurve2).Simplify(); pTmpPolycurve2.SplitAtPoint(pSplitPoint, bProject, bCreatePart, out bSplitted, out lNewPart, out lNewSeg); if (bSplitted) //更新pGeoCollection { pGeoCollection.RemoveGeometries(GeoCount, 1); pTmpGeoCollection = (IGeometryCollection)pTmpPolycurve2; pGeoCollection.AddGeometryCollection(pTmpGeoCollection); } GeoCount++; } } IGeometryCollection pGeometryCol = pGeoCollection; //被打断后的线的集合 for (int intCount = 0; intCount < pGeometryCol.GeometryCount; intCount++) { IPolycurve2 pPolyline = CommonFunction.BuildPolyLineFromSegmentCollection((ISegmentCollection)pGeometryCol.get_Geometry(intCount)); CommonFunction.AddFeature(m_MapControl, (IGeometry)pPolyline, m_App.CurrentEditLayer, pOldFeature, pArray); } pOldFeature.Delete(); } m_App.Workbench.CommandBarManager.Tools["2dmap.DFEditorTool.Undo"].SharedProps.Enabled = true; pWorkspaceEdit.StopEditOperation(); Reset(); }
/// <summary> /// Writes a 'GeometryCollection' to the stream. /// </summary> /// <param name="geomCollection">The polygon to write.</param> /// <param name="ordinates">The ordinates to write. <see cref="Ordinates.XY"/> are always written.</param> /// <param name="byteOrder">The byte order.</param> /// <param name="writer">The writer to use.</param> private void Write(IGeometryCollection geomCollection, Ordinates ordinates, ByteOrder byteOrder, BinaryWriter writer) { WriteHeader(PostGisGeometryType.GeometryCollection, HandleSRID ? geomCollection.SRID : -1, ordinates, byteOrder, writer); writer.Write(geomCollection.NumGeometries); Write(geomCollection.Geometries, ordinates, byteOrder, writer); }
/// <summary> /// 构造 TIN /// </summary> public bool constuctTIN1() { double minX = 0, minY = 0, maxX = 0, maxY = 0; InternalInterference.Grid.GridHelper.getInstance().getMinXY(ref minX, ref minY); InternalInterference.Grid.GridHelper.getInstance().getMaxXY(ref maxX, ref maxY); Hashtable ht = new Hashtable(); ht["minX"] = minX; ht["maxX"] = maxX; ht["minY"] = minY; ht["maxY"] = maxY; DataTable gridTable = IbatisHelper.ExecuteQueryForDataTable("GetTINVertexByArea", ht); if (gridTable.Rows.Count < 1) { return(false); } IDataset dataset = (IDataset)pFeatureLayer.FeatureClass; IWorkspace workspace = dataset.Workspace; IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace; workspaceEdit.StartEditing(true); workspaceEdit.StartEditOperation(); IFeatureCursor pFeatureCursor = pFeatureClass.Insert(true); IFeatureBuffer pFeatureBuffer; float x, y, z; List <IPoint> pts = new List <IPoint>(); //循环添加 int cnt = 0; //初始化进度信息 LoadInfo loadInfo = new LoadInfo(); loadInfo.count = gridTable.Rows.Count; loadInfo.loadCreate(); //循环添加 foreach (DataRow dataRow in gridTable.Rows) { if (cnt++ % 1000 == 0) { loadInfo.cnt = cnt; loadInfo.loadUpdate(); Console.WriteLine("已计算 " + cnt + "/" + gridTable.Rows.Count); } if (!(float.TryParse(dataRow["VertexX"].ToString(), out x) && float.TryParse(dataRow["VertexY"].ToString(), out y) && float.TryParse(dataRow["VertexHeight"].ToString(), out z))) { continue; } IPoint pointA = GeometryUtilities.ConstructPoint3D(x, y, z); pts.Add(pointA); if (pts.Count >= 3) { IGeometryCollection pGeometryColl = GeometryUtilities.ConstructMultiPath(pts); pFeatureBuffer = pFeatureClass.CreateFeatureBuffer(); pFeatureBuffer.Shape = pGeometryColl as IGeometry; pFeatureCursor.InsertFeature(pFeatureBuffer); pts.Clear(); } } //一次性提交 pFeatureCursor.Flush(); //stop editing workspaceEdit.StopEditOperation(); workspaceEdit.StopEditing(true); IFeatureClassManage pFeatureClassManage = (IFeatureClassManage)pFeatureClass; pFeatureClassManage.UpdateExtent(); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureClassManage); System.Runtime.InteropServices.Marshal.ReleaseComObject(dataset); System.Runtime.InteropServices.Marshal.ReleaseComObject(workspace); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor); //更新完成进度信息 loadInfo.cnt = cnt; loadInfo.loadUpdate(); //GISMapApplication.Instance.RefreshLayer(pFeatureLayer); return(true); }
public void Draw(Map map, IGraphics g, IGeometry geom, IStyle style, bool clip) { Validate(map, g, geom, style); VectorStyle s = (VectorStyle)style; OgcGeometryType type = geom.OgcGeometryType; switch (type) { case OgcGeometryType.Point: if (s.PointSymbolizer != null) { DrawPoint(s.PointSymbolizer, g, (IPoint)geom, map); return; } if (s.Symbol != null || s.PointColor == null) { DrawPoint(g, (IPoint)geom, s.Symbol, s.SymbolScale, s.SymbolOffset, s.SymbolRotation, map); return; } DrawPoint(g, (IPoint)geom, s.PointColor, s.PointSize, s.SymbolOffset, map); break; case OgcGeometryType.MultiPoint: if (s.PointSymbolizer != null) { DrawMultiPoint(s.PointSymbolizer, g, (IMultiPoint)geom, map); } if (s.Symbol != null || s.PointColor == null) { DrawMultiPoint(g, (IMultiPoint)geom, s.Symbol, s.SymbolScale, s.SymbolOffset, s.SymbolRotation, map); } else { DrawMultiPoint(g, (IMultiPoint)geom, s.PointColor, s.PointSize, s.SymbolOffset, map); } break; case OgcGeometryType.LineString: if (s.LineSymbolizer != null) { s.LineSymbolizer.Render(map, (ILineString)geom, g); return; } DrawLineString(g, (ILineString)geom, s.Line, map, s.LineOffset); return; case OgcGeometryType.MultiLineString: if (s.LineSymbolizer != null) { s.LineSymbolizer.Render(map, (IMultiLineString)geom, g); return; } DrawMultiLineString(g, (IMultiLineString)geom, s.Line, map, s.LineOffset); break; case OgcGeometryType.Polygon: if (s.EnableOutline) { DrawPolygon(g, (IPolygon)geom, s.Fill, s.Outline, clip, map); } else { DrawPolygon(g, (IPolygon)geom, s.Fill, null, clip, map); } break; case OgcGeometryType.MultiPolygon: if (s.EnableOutline) { DrawMultiPolygon(g, (IMultiPolygon)geom, s.Fill, s.Outline, clip, map); } else { DrawMultiPolygon(g, (IMultiPolygon)geom, s.Fill, null, clip, map); } break; case OgcGeometryType.GeometryCollection: IGeometryCollection coll = (IGeometryCollection)geom; for (int i = 0; i < coll.NumGeometries; i++) { Draw(map, g, coll[i], s, clip); } break; } }
/// <summary> /// /// </summary> /// <param name="gc"></param> private void AddCollection(IGeometryCollection gc) { for (int i = 0; i < gc.NumGeometries; i++) { IGeometry g = gc.GetGeometryN(i); Add(g); } }
private void SnapPoint() { IEngineSnapEnvironment engineEditor = Editor.UniqueInstance.EngineEditor as IEngineSnapEnvironment; IEngineEditSketch sketch = Editor.UniqueInstance.EngineEditor as IEngineEditSketch; IPointCollection points = sketch.Geometry as IPointCollection; bool flag = false; if (sketch.GeometryType == esriGeometryType.esriGeometryPolygon) { flag = true; } if ((points.PointCount != 1) && (!flag || (points.PointCount != 2))) { IEngineFeatureSnapAgent agent2 = engineEditor.get_SnapAgent(0) as IEngineFeatureSnapAgent; esriSpatialRelEnum esriSpatialRelIntersects = esriSpatialRelEnum.esriSpatialRelIntersects; if (agent2.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon) { esriSpatialRelIntersects = esriSpatialRelEnum.esriSpatialRelTouches; } IPoint lastPoint = sketch.LastPoint; List <IFeature> pFeatures = new List <IFeature>(); ISpatialFilter filter = new SpatialFilterClass { Geometry = lastPoint, SpatialRel = esriSpatialRelIntersects, SubFields = agent2.FeatureClass.OIDFieldName + "," + agent2.FeatureClass.ShapeFieldName, GeometryField = agent2.FeatureClass.ShapeFieldName }; IFeatureCursor o = agent2.FeatureClass.Search(filter, false); IFeature item = o.NextFeature(); while (item != null) { if (item.HasOID && !item.Shape.IsEmpty) { pFeatures.Add(item); item = o.NextFeature(); } } Marshal.ReleaseComObject(o); if (pFeatures.Count >= 1) { IPoint queryPoint = null; if (flag) { queryPoint = points.get_Point(points.PointCount - 3); } else { queryPoint = points.get_Point(points.PointCount - 2); } List <IFeature> list2 = new List <IFeature>(); filter = new SpatialFilterClass { Geometry = queryPoint, SpatialRel = esriSpatialRelIntersects, SubFields = agent2.FeatureClass.OIDFieldName + "," + agent2.FeatureClass.ShapeFieldName, GeometryField = agent2.FeatureClass.ShapeFieldName }; o = null; o = agent2.FeatureClass.Search(filter, false); item = o.NextFeature(); while (item != null) { if (item.HasOID && !item.Shape.IsEmpty) { list2.Add(item); item = o.NextFeature(); } } Marshal.ReleaseComObject(o); if (list2.Count >= 1) { IList <IFeature> list3 = new List <IFeature>(); for (int i = 0; i < list2.Count; i++) { if (this.ContainFeature(pFeatures, list2[i])) { list3.Add(list2[i]); } } IFeature feature2 = null; if (list3.Count == 1) { feature2 = list3[0]; } else { if (list3.Count == 0) { return; } if (list3.Count == pFeatures.Count) { IFeatureLayer pLayer = Editor.UniqueInstance.SnapLayers[0]; SnapExFeatures features = new SnapExFeatures(pFeatures, this._hookHelper, pLayer); features.ShowDialog(); if (features.Index == -1) { return; } feature2 = pFeatures[features.Index]; features = null; } } double hitDistance = -1.0; int hitSegmentIndex = -1; int hitPartIndex = -1; bool bRightSide = false; IGeometry geometry = this.ProjectGeometry(feature2.Shape); IHitTest test = geometry as IHitTest; if (test.HitTest(lastPoint, engineEditor.SnapTolerance, esriGeometryHitPartType.esriGeometryPartVertex, null, ref hitDistance, ref hitPartIndex, ref hitSegmentIndex, ref bRightSide)) { int num5 = -1; double num6 = -1.0; int num7 = -1; int num8 = -1; bool flag4 = false; int part = sketch.Part; IHitTest test2 = geometry as IHitTest; if (test2.HitTest(queryPoint, engineEditor.SnapTolerance, esriGeometryHitPartType.esriGeometryPartVertex, null, ref num6, ref num8, ref num7, ref flag4)) { IPolyline polyline3; if (flag) { num5 = points.PointCount - 2; } else { num5 = points.PointCount - 1; } IGeometryCollection geometrys = geometry as IGeometryCollection; IPointCollection points2 = geometrys.get_Geometry(hitPartIndex) as IPointCollection; IPolyline polyline = new PolylineClass(); IPolyline polyline2 = new PolylineClass(); IPointCollection points3 = polyline as IPointCollection; IPointCollection points4 = polyline2 as IPointCollection; object before = Missing.Value; object after = Missing.Value; IPoint inPoint = null; bool flag6 = false; if (num7 > hitSegmentIndex) { int num9 = hitSegmentIndex; hitSegmentIndex = num7; num7 = num9; flag6 = true; } int num10 = 0; if (flag) { for (num10 = num7; num10 <= hitSegmentIndex; num10++) { inPoint = points2.get_Point(num10); points3.AddPoint(inPoint, ref before, ref after); } int num11 = points2.PointCount - 1; for (num10 = hitSegmentIndex; num10 < num11; num10++) { inPoint = points2.get_Point(num10); points4.AddPoint(inPoint, ref before, ref after); } for (num10 = 0; num10 <= num7; num10++) { inPoint = points2.get_Point(num10); points4.AddPoint(inPoint, ref before, ref after); } if (polyline.Length <= polyline2.Length) { polyline3 = polyline; } else { polyline3 = polyline2; flag6 = true; } } else { num10 = num7; while (num10 <= hitSegmentIndex) { inPoint = points2.get_Point(num10); points3.AddPoint(inPoint, ref before, ref after); num10++; } polyline3 = polyline; } IPointCollection points5 = polyline3 as IPointCollection; int index = num5; if (flag6) { for (num10 = points5.PointCount - 2; num10 > 0; num10--) { IPoint newPoints = (points5.get_Point(num10) as IClone).Clone() as IPoint; points.InsertPoints(index, 1, ref newPoints); index++; } } else { for (num10 = 1; num10 < (points5.PointCount - 1); num10++) { IPoint point7 = (points5.get_Point(num10) as IClone).Clone() as IPoint; points.InsertPoints(index, 1, ref point7); index++; } } } } } } } }
/// <summary> /// 区域覆盖 /// </summary> /// <param name="mingxid"></param> /// <param name="mingyid"></param> /// <param name="maxgxid"></param> /// <param name="maxgyid"></param> public bool constuctAreaGrids(int mingxid, int mingyid, int maxgxid, int maxgyid, string layerName) { DataTable gridTable = new DataTable(); Hashtable ht = new Hashtable(); ht["MinGXID"] = mingxid; ht["MaxGXID"] = maxgxid; ht["MinGYID"] = mingyid; ht["MaxGYID"] = maxgyid; gridTable = IbatisHelper.ExecuteQueryForDataTable("GetSpecifiedAreaGrids", ht); if (gridTable.Rows.Count < 1) { return(false); } /* *<select id="GetSpecifiedAreaGrids" parameterClass="Hashtable"> * select a.GXID, a.GYID, a.eNodeB, a.CI, d.MinLong, d.MinLat, d.MaxLong, d.MaxLat, a.ReceivedPowerdbm, a.PathLoss from tbGridPathloss a , * (select c.GXID, c.GYID, c.eNodeB, c.CI, max(c.ReceivedPowerdbm) ReceivedPowerdbm from tbGridPathloss c where c.GXID between '$MinGXID$' and '$MaxGXID$' and c.GYID between '$MinGYID$' and '$MaxGYID$' group by c.gxid, c.gyid, c.eNodeB, c.ci having max(c.ReceivedPowerdbm) > -130 ) b, * tbGridDem d * where a.gxid = b.gxid and a.gyid = b.gyid and a.eNodeB = b.eNodeB and a.ci = b.ci and a.gxid = d.gxid and a.gyid = d.gyid * </select> */ IFeatureWorkspace featureWorkspace = MapWorkSpace.getWorkSpace(); IFeatureClass fclass = featureWorkspace.OpenFeatureClass(layerName); //IFeatureLayer flayer = new FeatureLayer(); pFeatureLayer.FeatureClass = pFeatureClass; //IFeatureLayer flayer = GISMapApplication.Instance.GetLayer(LayerNames.AreaCoverGrids) as IFeatureLayer; //FeatureUtilities.DeleteFeatureLayerFeatrues(flayer); //IFeatureClass fclass = flayer.FeatureClass; IDataset dataset = (IDataset)fclass; IWorkspace workspace = dataset.Workspace; //Cast for an IWorkspaceEdit IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace; //start an edit session and operation workspaceEdit.StartEditing(true); workspaceEdit.StartEditOperation(); IFeatureCursor pFeatureCursor = fclass.Insert(true); IFeatureBuffer pFeatureBuffer; //int gxid, gyid, lac, ci; //float x1, y1, x2, y2; //float recePower, pathLoss; int lac, ci, gxid, gyid, level; double x1, y1, x2, y2, z; double recePower, pathLoss; double gbaseheight = GridHelper.getInstance().getGBaseHeight(); double gheight = GridHelper.getInstance().getGHeight(); //循环添加 int cnt = 0; //循环添加 foreach (DataRow dataRow in gridTable.Rows) { if (cnt++ % 1000 == 0) { Console.WriteLine("已计算 " + cnt + "/" + gridTable.Rows.Count); } gxid = int.Parse(dataRow["GXID"].ToString()); gyid = int.Parse(dataRow["GYID"].ToString()); level = int.Parse(dataRow["Level"].ToString()); Geometric.Point p = GridHelper.getInstance().GridToGeo(gxid, gyid); double lon = p.X; double lat = p.Y; //lac = int.Parse(dataRow["eNodeB"].ToString()); //ci = int.Parse(dataRow["CI"].ToString()); recePower = double.Parse(dataRow["ReceivedPowerdbm"].ToString()); pathLoss = double.Parse(dataRow["PathLoss"].ToString()); if (!(double.TryParse(dataRow["MinX"].ToString(), out x1) && double.TryParse(dataRow["MinY"].ToString(), out y1) && double.TryParse(dataRow["MaxX"].ToString(), out x2) && double.TryParse(dataRow["MaxY"].ToString(), out y2))) { continue; } z = gheight * (level - 1) + gbaseheight; IPoint pointA = GeometryUtilities.ConstructPoint3D(x1, y1, z); IPoint pointB = GeometryUtilities.ConstructPoint3D(x2, y1, z); IPoint pointC = GeometryUtilities.ConstructPoint3D(x2, y2, z); IPoint pointD = GeometryUtilities.ConstructPoint3D(x1, y2, z); IGeometryCollection pGeometryColl = GeometryUtilities.ConstructPolygon(new IPoint[] { pointA, pointB, pointC, pointD }); GeometryUtilities.MakeZAware(pGeometryColl as IGeometry); pFeatureBuffer = pFeatureClass.CreateFeatureBuffer(); pFeatureBuffer.Shape = pGeometryColl as IGeometry; pFeatureBuffer.set_Value(this.GXIDIndex, gxid); pFeatureBuffer.set_Value(this.GYIDIndex, gyid); pFeatureBuffer.set_Value(this.eNodeBIndex, 0); pFeatureBuffer.set_Value(this.CIIndex, 0); pFeatureBuffer.set_Value(this.cellNameIndex, ""); pFeatureBuffer.set_Value(this.LongitudeIndex, lon); pFeatureBuffer.set_Value(this.LatitudeIndex, lat); pFeatureBuffer.set_Value(this.LevelIndex, level); if (recePower > -41) { pFeatureBuffer.set_Value(this.RecePowerIndex, -41); } //else if(recePower < -110) // pFeatureBuffer.set_Value(this.RecePowerIndex, -110); else { pFeatureBuffer.set_Value(this.RecePowerIndex, recePower); } pFeatureBuffer.set_Value(this.PathLossIndex, pathLoss); pFeatureCursor.InsertFeature(pFeatureBuffer); } //一次性提交 pFeatureCursor.Flush(); //stop editing workspaceEdit.StopEditOperation(); workspaceEdit.StopEditing(true); IFeatureClassManage pFeatureClassManage = (IFeatureClassManage)pFeatureClass; pFeatureClassManage.UpdateExtent(); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureClassManage); System.Runtime.InteropServices.Marshal.ReleaseComObject(dataset); System.Runtime.InteropServices.Marshal.ReleaseComObject(workspace); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor); //GISMapApplication.Instance.RefreshLayer(pFeatureLayer); return(true); }
/// <summary> /// 构造小区覆盖网格 /// </summary> /// <param name="cellname"></param> /// <param name="enodeb"></param> /// <param name="ci"></param> public bool constuctCellGrids(string cellname, int enodeb, int ci) { DataTable gridTable = new DataTable(); Hashtable ht = new Hashtable(); ht["eNodeB"] = enodeb; ht["CI"] = ci; gridTable = IbatisHelper.ExecuteQueryForDataTable("GetSpecifiedCellGrids", ht); if (gridTable.Rows.Count < 1) { return(false); } IDataset dataset = (IDataset)pFeatureLayer.FeatureClass; IWorkspace workspace = dataset.Workspace; IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace; workspaceEdit.StartEditing(true); workspaceEdit.StartEditOperation(); IFeatureCursor pFeatureCursor = pFeatureClass.Insert(true); IFeatureBuffer pFeatureBuffer; int gxid, gyid, level; double x1, y1, x2, y2, z; double recePower, pathLoss; double gheight = GridHelper.getInstance().getGHeight(); //循环添加 int cnt = 0; //初始化进度信息 LoadInfo loadInfo = new LoadInfo(); loadInfo.count = gridTable.Rows.Count; loadInfo.loadCreate(); foreach (DataRow dataRow in gridTable.Rows) { if (cnt++ % 1000 == 0) { loadInfo.cnt = cnt; loadInfo.loadUpdate(); Console.WriteLine("已计算 " + cnt + "/" + gridTable.Rows.Count); } gxid = int.Parse(dataRow["Gxid"].ToString()); gyid = int.Parse(dataRow["Gyid"].ToString()); level = int.Parse(dataRow["Level"].ToString()); Geometric.Point p = GridHelper.getInstance().GridToGeo(gxid, gyid); double lon = p.X; double lat = p.Y; //if (!(float.TryParse(dataRow["MinX"].ToString(), out x1) && float.TryParse(dataRow["MinY"].ToString(), out y1) && float.TryParse(dataRow["MaxX"].ToString(), out x2) && float.TryParse(dataRow["MaxY"].ToString(), out y2) && float.TryParse(dataRow["ReceivedPowerdbm"].ToString(), out recePower) && float.TryParse(dataRow["PathLoss"].ToString(), out pathLoss))) // continue; if (!(double.TryParse(dataRow["MinX"].ToString(), out x1) && double.TryParse(dataRow["MinY"].ToString(), out y1))) { continue; } if (!(double.TryParse(dataRow["MaxX"].ToString(), out x2) && double.TryParse(dataRow["MaxY"].ToString(), out y2))) { continue; } if (!(double.TryParse(dataRow["ReceivedPowerdbm"].ToString(), out recePower) && double.TryParse(dataRow["PathLoss"].ToString(), out pathLoss))) { continue; } z = gheight * level; IPoint pointA = GeometryUtilities.ConstructPoint3D(x1, y1, z); IPoint pointB = GeometryUtilities.ConstructPoint3D(x2, y1, z); IPoint pointC = GeometryUtilities.ConstructPoint3D(x2, y2, z); IPoint pointD = GeometryUtilities.ConstructPoint3D(x1, y2, z); IGeometryCollection pGeometryColl = GeometryUtilities.ConstructPolygon(new IPoint[] { pointA, pointB, pointC, pointD }); GeometryUtilities.MakeZAware(pGeometryColl as IGeometry); pFeatureBuffer = pFeatureClass.CreateFeatureBuffer(); pFeatureBuffer.Shape = pGeometryColl as IGeometry; pFeatureBuffer.set_Value(this.GXIDIndex, gxid); pFeatureBuffer.set_Value(this.GYIDIndex, gyid); pFeatureBuffer.set_Value(this.eNodeBIndex, enodeb); pFeatureBuffer.set_Value(this.CIIndex, ci); pFeatureBuffer.set_Value(this.cellNameIndex, cellname); pFeatureBuffer.set_Value(this.LevelIndex, level); pFeatureBuffer.set_Value(this.LongitudeIndex, lon); pFeatureBuffer.set_Value(this.LatitudeIndex, lat); if (recePower > -41) { pFeatureBuffer.set_Value(this.RecePowerIndex, -41); } //else if(recePower < -110) // pFeatureBuffer.set_Value(this.RecePowerIndex, -110); else { pFeatureBuffer.set_Value(this.RecePowerIndex, recePower); } pFeatureBuffer.set_Value(this.PathLossIndex, pathLoss); pFeatureCursor.InsertFeature(pFeatureBuffer); //释放AO对象 System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureBuffer); System.Runtime.InteropServices.Marshal.ReleaseComObject(pGeometryColl); } //一次性提交 pFeatureCursor.Flush(); //stop editing workspaceEdit.StopEditOperation(); workspaceEdit.StopEditing(true); IFeatureClassManage pFeatureClassManage = (IFeatureClassManage)pFeatureClass; pFeatureClassManage.UpdateExtent(); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureClassManage); System.Runtime.InteropServices.Marshal.ReleaseComObject(dataset); System.Runtime.InteropServices.Marshal.ReleaseComObject(workspace); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor); //更新完成进度信息 loadInfo.cnt = cnt; loadInfo.loadUpdate(); //GISMapApplication.Instance.RefreshLayer(pFeatureLayer); return(true); }
private void AddGeometryCollection(SqlGeometryBuilder builder, IGeometryCollection geometry, OpenGisGeometryType type) { builder.BeginGeometry(type); Array.ForEach(geometry.Geometries, geometry1 => AddGeometry(builder, geometry1)); builder.EndGeometry(); }
public bool constuctGrid3Ds(int mingxid, int maxgxid, int mingyid, int maxgyid, short type) { DataTable gridTable = new DataTable(); Hashtable para = new Hashtable(); para["minGXID"] = mingxid; para["maxGXID"] = maxgxid; para["minGYID"] = mingyid; para["maxGYID"] = maxgyid; para["type"] = type; gridTable = IbatisHelper.ExecuteQueryForDataTable("getDefect", para); if (gridTable.Rows.Count < 1) { return(false); } IDataset dataset = (IDataset)pFeatureLayer.FeatureClass; IWorkspace workspace = dataset.Workspace; //Cast for an IWorkspaceEdit IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace; //start an edit session and operation workspaceEdit.StartEditing(true); workspaceEdit.StartEditOperation(); IFeatureCursor pFeatureCursor = pFeatureClass.Insert(true); IFeatureBuffer pFeatureBuffer; int gxid, gyid, level; double x1, y1, x2, y2, z; double recePower; double gbaseheight = GridHelper.getInstance().getGBaseHeight(); double gheight = GridHelper.getInstance().getGHeight(); //循环添加 int cnt = 0; foreach (DataRow dataRow in gridTable.Rows) { if (++cnt % 100 == 0) { Console.WriteLine(cnt + "/" + gridTable.Rows.Count); } gxid = int.Parse(dataRow["GXID"].ToString()); gyid = int.Parse(dataRow["GYID"].ToString()); level = int.Parse(dataRow["GZID"].ToString()); if (!(double.TryParse(dataRow["MinX"].ToString(), out x1) && double.TryParse(dataRow["MinY"].ToString(), out y1))) { continue; } if (!(double.TryParse(dataRow["MaxX"].ToString(), out x2) && double.TryParse(dataRow["MaxY"].ToString(), out y2))) { continue; } if (!(double.TryParse(dataRow["ReceivedPowerdbm"].ToString(), out recePower))) { continue; } z = gheight * level; IPoint pointA = GeometryUtilities.ConstructPoint3D(x1, y1, z); IPoint pointB = GeometryUtilities.ConstructPoint3D(x2, y1, z); IPoint pointC = GeometryUtilities.ConstructPoint3D(x2, y2, z); IPoint pointD = GeometryUtilities.ConstructPoint3D(x1, y2, z); IGeometryCollection pGeometryColl = GeometryUtilities.ConstructPolygon(new IPoint[] { pointA, pointB, pointC, pointD }); GeometryUtilities.MakeZAware(pGeometryColl as IGeometry); pFeatureBuffer = pFeatureClass.CreateFeatureBuffer(); pFeatureBuffer.Shape = pGeometryColl as IGeometry; pFeatureBuffer.set_Value(this.GXIDIndex, gxid); pFeatureBuffer.set_Value(this.GYIDIndex, gyid); pFeatureBuffer.set_Value(this.LevelIndex, level); if (recePower > -41) { pFeatureBuffer.set_Value(this.RecePowerIndex, -41); } else { pFeatureBuffer.set_Value(this.RecePowerIndex, recePower); } pFeatureCursor.InsertFeature(pFeatureBuffer); } //一次性提交 pFeatureCursor.Flush(); //stop editing workspaceEdit.StopEditOperation(); workspaceEdit.StopEditing(true); //IFeatureClassManage pFeatureClassManage = (IFeatureClassManage)pFeatureClass; //pFeatureClassManage.UpdateExtent(); System.Runtime.InteropServices.Marshal.ReleaseComObject(dataset); System.Runtime.InteropServices.Marshal.ReleaseComObject(workspace); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor); //GISMapApplication.Instance.RefreshLayer(pFeatureLayer); return(true); }
/// <summary> /// Transforms a <see cref="GeoAPI.Geometries.IGeometryCollection"/>. /// </summary> /// <param name="geoms">GeometryCollection to transform</param> /// <param name="from">Source Projection</param> /// <param name="to">Target Projection</param> /// <param name="toFactory">The factory to create geometries for <paramref name="to"/></param> /// <returns>Transformed GeometryCollection</returns> public static IGeometryCollection TransformGeometryCollection(IGeometryCollection geoms, ProjectionInfo from, ProjectionInfo to, IGeometryFactory toFactory) { var gOut = new IGeometry[geoms.Count]; for (var i = 0; i < geoms.Count; i++) gOut[i] = TransformGeometry(geoms.GetGeometryN(i), from, to, toFactory); return toFactory.CreateGeometryCollection(gOut); }
public void OnMouseDown(int button, int shift, int x, int y) { if (button != 2) { try { IPoint pGeometry = this.m_hookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y); IFeatureClass featureClass = Editor.UniqueInstance.TargetLayer.FeatureClass; ISpatialFilter queryFilter = new SpatialFilterClass { Geometry = pGeometry, GeometryField = featureClass.ShapeFieldName, SubFields = featureClass.OIDFieldName, SpatialRel = esriSpatialRelEnum.esriSpatialRelWithin }; IFeatureCursor o = Editor.UniqueInstance.TargetLayer.Search(queryFilter, false); IFeature feature = o.NextFeature(); IFeature feature2 = o.NextFeature(); Marshal.ReleaseComObject(o); o = null; if ((feature != null) && (feature2 != null)) { feature = Editor.UniqueInstance.TargetLayer.FeatureClass.GetFeature(feature.OID); feature2 = Editor.UniqueInstance.TargetLayer.FeatureClass.GetFeature(feature2.OID); ITopologicalOperator2 shape = feature.Shape as ITopologicalOperator2; IGeometry geometry1 = feature2.Shape; IGeometry other = shape.Intersect(feature2.Shape, esriGeometryDimension.esriGeometry2Dimension); if (!other.IsEmpty) { pGeometry = GISFunFactory.UnitFun.ConvertPoject(pGeometry, other.SpatialReference) as IPoint; IGeometryCollection geometrys = other as IGeometryCollection; if (geometrys.GeometryCount > 1) { for (int i = 0; i < geometrys.GeometryCount; i++) { IGeometry inGeometry = geometrys.get_Geometry(i); if (!inGeometry.IsEmpty) { if (inGeometry.GeometryType == esriGeometryType.esriGeometryRing) { object missing = System.Type.Missing; IGeometryCollection geometrys2 = new PolygonClass(); geometrys2.AddGeometry(inGeometry, ref missing, ref missing); IPolygon polygon = geometrys2 as IPolygon; inGeometry = polygon; } IRelationalOperator operator2 = inGeometry as IRelationalOperator; if ((operator2 != null) && operator2.Contains(pGeometry)) { other = inGeometry; break; } } } } else { IRelationalOperator operator3 = other as IRelationalOperator; if (!operator3.Contains(pGeometry)) { return; } } feature = Editor.UniqueInstance.TargetLayer.FeatureClass.GetFeature(feature.OID); feature2 = Editor.UniqueInstance.TargetLayer.FeatureClass.GetFeature(feature2.OID); if (other.GeometryType != esriGeometryType.esriGeometryPolygon) { IPolygon polygon2 = new PolygonClass { SpatialReference = other.SpatialReference }; IPointCollection newPoints = other as IPointCollection; (polygon2 as IPointCollection).AddPointCollection(newPoints); other = polygon2; } Editor.UniqueInstance.StartEditOperation(); ITopologicalOperator2 operator4 = feature.Shape as ITopologicalOperator2; IGeometry geometry3 = operator4.Difference(other); if (geometry3.IsEmpty) { feature.Delete(); } else { feature.Shape = geometry3; feature.Store(); } geometry3 = (feature2.Shape as ITopologicalOperator2).Difference(other); if (geometry3.IsEmpty) { feature2.Delete(); } else { feature2.Shape = geometry3; feature2.Store(); } Editor.UniqueInstance.StopEditOperation(); (Editor.UniqueInstance.TargetLayer as IFeatureSelection).Clear(); this.m_hookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection | esriViewDrawPhase.esriViewGeography, null, this.m_hookHelper.ActiveView.Extent); MessageBox.Show("修改完成!", "提示"); } } } catch (Exception exception) { Editor.UniqueInstance.AbortEditOperation(); this.mErrOpt.ErrorOperate(this.mSubSysName, "ShapeEdit.OverlapDelete", "OnMouseDown", exception.GetHashCode().ToString(), exception.Source, exception.Message, "", "", ""); MessageBox.Show("修改出错!", "提示"); } } }
/// <summary> /// /// </summary> /// <param name="geometry"></param> /// <returns></returns> protected virtual int SetByteStream(IGeometryCollection geometry) { int count = INIT_COUNT; count += 4; foreach (Geometry geom in geometry.Geometries) count += SetByteStream(geom); return count; }
/// <summary> /// 绘制曲线部分 /// </summary> /// <params name="lyr">推断断层</params> /// <params name="newplines">延长点构造的线</params> /// <params name="originlines">原始点构造的线</params> private void AddCurveToMap(IFeatureLayer lyr, List <IPolyline> newplines, List <IPolyline> originlines) { IFeatureClass Featureclass = lyr.FeatureClass; IWorkspaceEdit workspace = (IWorkspaceEdit)(Featureclass as IDataset).Workspace; workspace.StartEditing(true); workspace.StartEditOperation(); object missing = Type.Missing; //揭露断层上的曲线对象 IGeometry geom = new PolylineClass(); geom.SpatialReference = Global.spatialref; IGeometryCollection outgeomcols = geom as IGeometryCollection; IFeature fea = Featureclass.CreateFeature(); ISegmentCollection newpath = new PathClass(); int kindpos = Featureclass.Fields.FindField(GIS.GIS_Const.FIELD_TYPE); int bidpos = Featureclass.Fields.FindField(GIS.GIS_Const.FIELD_BID); for (int i = 0; i < newplines.Count; i++) { ILine lin = new LineClass(); lin.SpatialReference = Global.spatialref; //直线段 IPath path = new PathClass(); if (i == 0) { lin.FromPoint = newplines[i].FromPoint; lin.ToPoint = originlines[i].ToPoint; } else if (i == originlines.Count - 1) { lin.FromPoint = originlines[i].FromPoint; lin.ToPoint = newplines[i].ToPoint; } else { lin.FromPoint = originlines[i].FromPoint; lin.ToPoint = originlines[i].ToPoint; } newpath.AddSegment(lin as ISegment, ref missing, ref missing); //曲线段 if (i < newplines.Count - 1) { IBezierCurveGEN bezier = new BezierCurveClass(); IPoint[] pntcontrols = new IPoint[4]; pntcontrols[0] = originlines[i].ToPoint; pntcontrols[1] = newplines[i].ToPoint; pntcontrols[2] = newplines[i + 1].FromPoint; pntcontrols[3] = originlines[i + 1].FromPoint; bezier.PutCoords(ref pntcontrols); newpath.AddSegment(bezier as ISegment, ref missing, ref missing); } } outgeomcols.AddGeometry(newpath as IGeometry, ref missing, ref missing); int index = fea.Fields.FindField(GIS_Const.FIELD_SHAPE); IGeometryDef geometryDef = fea.Fields.get_Field(index).GeometryDef as IGeometryDef; if (geometryDef.HasZ) { IZAware pZAware = (IZAware)outgeomcols; pZAware.ZAware = true; } fea.Shape = outgeomcols as IPolyline; fea.set_Value(kindpos, 1); fea.set_Value(bidpos, BID); fea.Store(); //外围曲线绘制 ITopologicalOperator2 top = outgeomcols as ITopologicalOperator2; if (!top.IsSimple) { top.Simplify(); } IConstructCurve curve = new PolylineClass(); curve.ConstructOffset(outgeomcols as IPolyline, -3, ref missing, ref missing); IPolyline plinnew = curve as IPolyline; plinnew.SpatialReference = Global.spatialref; plinnew.FromPoint = newplines[0].FromPoint; plinnew.ToPoint = newplines[newplines.Count - 1].ToPoint; IFeature outcurve = Featureclass.CreateFeature(); outcurve.set_Value(kindpos, 2); outcurve.set_Value(bidpos, BID); outcurve.Shape = plinnew; outcurve.Store(); //结束编辑 workspace.StopEditOperation(); workspace.StopEditing(true); //定位跳转 Global.commonclss.JumpToGeometry(plinnew); }
/// <summary> /// Reads a generic stream containing geographic data saved as shapefile structure, /// and returns a collection of all the features contained. /// Since NTS Geometry Model not support Z and M data, those informations are ignored if presents in shapefile. /// </summary> /// <param name="stream">Shapefile data stream.</param> /// <returns><c>GeometryCollection</c> containing all geometries in shapefile.</returns> protected IGeometryCollection Read(Stream stream) { // Read big endian values using (BigEndianBinaryReader beReader = new BigEndianBinaryReader(stream)) { // Verify File Code int fileCode = beReader.ReadInt32BE(); Debug.Assert(fileCode == 9994); stream.Seek(20, SeekOrigin.Current); length = beReader.ReadInt32BE(); // Read little endian values using (BinaryReader leReader = new BinaryReader(stream)) { ArrayList list = null; // Verify Version int version = leReader.ReadInt32(); Debug.Assert(version == 1000); // ShapeTypes int shapeType = leReader.ReadInt32(); switch ((ShapeGeometryTypes)shapeType) { case ShapeGeometryTypes.Point: case ShapeGeometryTypes.PointZ: case ShapeGeometryTypes.PointM: case ShapeGeometryTypes.PointZM: list = new ArrayList(ReadPointData(stream)); break; case ShapeGeometryTypes.LineString: case ShapeGeometryTypes.LineStringZ: case ShapeGeometryTypes.LineStringM: case ShapeGeometryTypes.LineStringZM: list = new ArrayList(ReadLineStringData(stream)); break; case ShapeGeometryTypes.Polygon: case ShapeGeometryTypes.PolygonZ: case ShapeGeometryTypes.PolygonM: case ShapeGeometryTypes.PolygonZM: list = new ArrayList(ReadPolygonData(stream)); break; case ShapeGeometryTypes.MultiPoint: case ShapeGeometryTypes.MultiPointZ: case ShapeGeometryTypes.MultiPointM: case ShapeGeometryTypes.MultiPointZM: list = new ArrayList(ReadMultiPointData(stream)); break; case ShapeGeometryTypes.MultiPatch: throw new NotImplementedException("FeatureType " + shapeType + " not supported."); default: throw new ArgumentOutOfRangeException("FeatureType " + shapeType + " not recognized by the system"); } IGeometryCollection collection = shapeReader.CreateGeometryCollection(list); return(collection); } } }
public void Write(string filename, IGeometryCollection geometryCollection, bool writeDummyDbf = true) { WriteGeometryCollection(filename, geometryCollection, writeDummyDbf); }
private void btnAddFeature_Click(object sender, EventArgs e) { IPoint pPoint1 = new PointClass(); pPoint1.PutCoords(82.1935, 21.5459); IPoint pPoint2 = new PointClass(); pPoint2.PutCoords(89.0913, 21.6609); IPoint pPoint3 = new PointClass(); pPoint3.PutCoords(88.9763, 15.6828); IPoint pPoint4 = new PointClass(); pPoint4.PutCoords(79.7793, 15.5679); // 创建一个环 IRing pRing = new RingClass(); ISegmentCollection pSegmentCollection = pRing as ISegmentCollection; object Missing1 = Type.Missing; object Missing2 = Type.Missing; ILine pLine = new LineClass(); pLine.PutCoords(pPoint1, pPoint2); pSegmentCollection.AddSegment(pLine as ISegment, ref Missing1, ref Missing2); pLine = new LineClass(); pLine.PutCoords(pPoint2, pPoint3); pSegmentCollection.AddSegment(pLine as ISegment, ref Missing1, ref Missing2); pLine = new LineClass(); pLine.PutCoords(pPoint3, pPoint4); pSegmentCollection.AddSegment(pLine as ISegment, ref Missing1, ref Missing2); pLine = new LineClass(); pLine.PutCoords(pPoint4, pPoint1); pSegmentCollection.AddSegment(pLine as ISegment, ref Missing1, ref Missing2); pRing.Close(); // 创建多边形 IPolygon pPolygon = new PolygonClass(); IGeometryCollection pGeometryCollection = pPolygon as IGeometryCollection; pGeometryCollection.AddGeometry(pRing, ref Missing1, ref Missing2); // 显示多边形 ISimpleFillSymbol pSimpleFillSymbol = new SimpleFillSymbolClass(); IRgbColor pColor = new RgbColorClass(); pColor.Red = 255; pColor.Blue = 0; pColor.Green = 0; pSimpleFillSymbol.Style = esriSimpleFillStyle.esriSFSDiagonalCross; pSimpleFillSymbol.Color = pColor; IFillShapeElement pFillShapeElement = new PolygonElementClass(); pFillShapeElement.Symbol = pSimpleFillSymbol; IElement pElement = pFillShapeElement as IElement; pElement.Geometry = pPolygon as IGeometry; IGraphicsContainer pGraphicsContainer = MainMap.Map as IGraphicsContainer; pGraphicsContainer.AddElement(pElement, 0); MainMap.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null); }
/// <summary> /// Method to write a collection of geometries to a shapefile on disk. /// </summary> /// <remarks> /// Assumes the type given for the first geometry is the same for all subsequent geometries. /// For example, is, if the first Geometry is a Multi-polygon/ Polygon, the subsequent geometies are /// Muli-polygon/ polygon and not lines or points. /// The dbase file for the corresponding shapefile contains one column called row. It contains /// the row number. /// </remarks> /// <param name="filename">The filename to write to (minus the .shp extension).</param> /// <param name="geometryCollection">The GeometryCollection to write.</param> /// <param name="writeDummyDbf">Set to true to create an empty DBF-file along with the shp-file</param> public static void WriteGeometryCollection(string filename, IGeometryCollection geometryCollection, bool writeDummyDbf = true) { WriteGeometryCollection(new ShapefileStreamProviderRegistry(filename, false, false, false), geometryCollection, writeDummyDbf); }
/// <summary> /// 通过鼠标点击获取观察点与被观察点同时进行两点间通视分析 /// </summary> /// <param name="Button"></param> /// <param name="Shift"></param> /// <param name="X"></param> /// <param name="Y"></param> public override void OnMouseDown(int Button, int Shift, int X, int Y) { if (m_frm3DLineOfSight.m_Layer == null || m_frm3DLineOfSight.m_Surface == null) { MessageBox.Show("请设置有效的表面数据", "提示!"); return; } if (m_frm3DLineOfSight.txtObsOffset.Text == "" || m_frm3DLineOfSight.txtTarOffset.Text == "") { MessageBox.Show("观察点高度和被观察点高度不能为空", "提示!"); return; } m_frm3DLineOfSight.TopMost = true; ISceneGraph pSceneGraph = m_sceneHookHelper.SceneGraph; m_pNewLineFeedback = new NewLineFeedbackClass(); IPolyline pPolyline = m_pNewLineFeedback.Stop(); //用于判断是否已经获取两点 ISceneControl pSceneControl = m_sceneHookHelper.Hook as ISceneControl; Cls3DModulsefun pCls3DModulsefun = new Cls3DModulsefun(); //用于绘制通视分析结果的方法 object pOwner; object pObject; ESRI.ArcGIS.Geometry.IPoint pPoint = new ESRI.ArcGIS.Geometry.PointClass(); pSceneGraph.Locate(pSceneGraph.ActiveViewer, X, Y, esriScenePickMode.esriScenePickGeography, true, out pPoint, out pOwner, out pObject);//获取鼠标点击的位置并转化为地理坐标 if (pPoint == null) { return; } ESRI.ArcGIS.Geometry.IPoint pFlashPoint = new ESRI.ArcGIS.Geometry.PointClass(); IClone pClone = pPoint as IClone; pFlashPoint = pClone.Clone() as ESRI.ArcGIS.Geometry.IPoint; pFlashPoint.Z = pFlashPoint.Z / pSceneGraph.VerticalExaggeration; pFlashPoint.SpatialReference = pSceneGraph.Scene.SpatialReference; IDisplay3D pDisplay = pSceneGraph as IDisplay3D; pDisplay.FlashLocation(pFlashPoint);//闪烁显示被点击的位置 IGeometry pGeometry = null; if (m_pScenePoints == null) { m_pScenePoints = new PolylineClass(); pGeometry = m_pScenePoints as IGeometry; pGeometry.SpatialReference = pSceneGraph.Scene.SpatialReference; } object before = Type.Missing; object after = Type.Missing; m_pScenePoints.AddPoint(pPoint, ref before, ref after);//添加获取的点到点集合中 if (m_pScenePoints.PointCount == 2) { pClone = m_pScenePoints as IClone; pPolyline = pClone.Clone() as ESRI.ArcGIS.Geometry.IPolyline;//当点集合中点数达到两个时生成一条线用于判断观察点与被观察点是否确定 m_pScenePoints = null; } if (pPolyline != null) { m_pScenePoints = null; ISurface pSurface = m_SurFace; ESRI.ArcGIS.Geometry.IPoint fPoint = pPolyline.FromPoint; //获取观察点 fPoint.Z = pSurface.GetElevation(fPoint); //获取观察点的高程 ESRI.ArcGIS.Geometry.IPoint tPoint = pPolyline.ToPoint; tPoint.Z = pSurface.GetElevation(tPoint); if (pSurface.IsVoidZ(fPoint.Z) || pSurface.IsVoidZ(tPoint.Z)) { return; } fPoint.Z = fPoint.Z + Convert.ToDouble(m_frm3DLineOfSight.txtObsOffset.Text);//观察者的高度加上观察者所在的高程才是观察点实际的高程 tPoint.Z = tPoint.Z + Convert.ToDouble(m_frm3DLineOfSight.txtTarOffset.Text); ESRI.ArcGIS.Geometry.IPoint pObstruct; IPolyline pVisPolyline; IPolyline pInVisPolyline; bool bIsVis; object pRefractionFactor = Type.Missing; //进行两点间的通视分析 pSurface.GetLineOfSight(fPoint, tPoint, out pObstruct, out pVisPolyline, out pInVisPolyline, out bIsVis, m_frm3DLineOfSight.checkBoxCurv.Checked, m_frm3DLineOfSight.checkBoxCurv.Checked, ref pRefractionFactor); ISimpleLineSymbol pSimpleLineSymbol = new SimpleLineSymbolClass(); pSimpleLineSymbol.Width = 2; pSimpleLineSymbol.Style = esriSimpleLineStyle.esriSLSSolid; //绘制可视与不可视的沿地表线要素 if (pVisPolyline != null) { pSimpleLineSymbol.Color = Cls3DMarkDraw.getRGB(0, 255, 0); pCls3DModulsefun.AddGraphic(pSceneControl, pVisPolyline as IGeometry, pSimpleLineSymbol as ISymbol); } if (pInVisPolyline != null) { pSimpleLineSymbol.Color = Cls3DMarkDraw.getRGB(255, 0, 0); pCls3DModulsefun.AddGraphic(pSceneControl, pInVisPolyline as IGeometry, pSimpleLineSymbol as ISymbol); } IGeometryCollection pVisPatch = new MultiPatchClass();//用于存储可视域的要素 pGeometry = pVisPatch as IGeometry; pGeometry.SpatialReference = pSceneGraph.Scene.SpatialReference; double dTargetHeightForVis = 0; ISimpleFillSymbol pSimpleFillSymbol = new SimpleFillSymbolClass(); IGeometryCollection pInVisPatch = new MultiPatchClass();//存储不可视域的要素 pGeometry = pInVisPatch as IGeometry; pGeometry.SpatialReference = pSceneGraph.Scene.SpatialReference; IGeometryCollection pPathGeo = pInVisPolyline as IGeometryCollection; if (pPathGeo != null) { //下面的作用是将不可视域线每段path生成线要素进行绘制 张琪 20110623 for (int i = 0; i < pPathGeo.GeometryCount; i++) { IGeometryCollection pInPolyline = new PolylineClass(); IPath path = pPathGeo.get_Geometry(i) as IPath; pInPolyline.AddGeometry(path as IGeometry, ref before, ref after); pCls3DModulsefun.CreateVerticalLOSPatches(bIsVis, fPoint, tPoint, pVisPolyline, pInPolyline as IPolyline, pVisPatch, pInVisPatch, dTargetHeightForVis); } } else//当不可视域为空时,直接分析生成可视域与不可视域 { pCls3DModulsefun.CreateVerticalLOSPatches(bIsVis, fPoint, tPoint, pVisPolyline, pInVisPolyline, pVisPatch, pInVisPatch, dTargetHeightForVis); } // // 对可视域与不可视域要素在场景中绘制出来 if (pInVisPatch != null) { pSimpleFillSymbol.Color = Cls3DMarkDraw.getRGB(255, 0, 0); pCls3DModulsefun.AddGraphic(pSceneControl, pInVisPatch as IGeometry, pSimpleFillSymbol as ISymbol); } if (pVisPatch != null) { pSimpleFillSymbol.Color = Cls3DMarkDraw.getRGB(0, 255, 0); pCls3DModulsefun.AddGraphic(pSceneControl, pVisPatch as IGeometry, pSimpleFillSymbol as ISymbol); } } }
public static GeoAPI.Geometries.IMultiPolygon ConvertTo(ESRI.ArcGIS.Geometry.IPolygon4 polygon) { GisSharpBlog.NetTopologySuite.Geometries.MultiPolygon output = null; List <GeoAPI.Geometries.IPolygon> list = new List <GeoAPI.Geometries.IPolygon>(); //IPolygon4.ExteriorRingBag should be used instead of IPolygon.QueryExteriorRings, //which does not work in .NET because of C-Style Arrays IGeometryBag exteriorRings = polygon.ExteriorRingBag; //For each exterior rings find the number of interior rings associated with it and print it IEnumGeometry exteriorRingsEnum = exteriorRings as IEnumGeometry; exteriorRingsEnum.Reset(); IRing currentExteriorRing = exteriorRingsEnum.Next() as IRing; while (currentExteriorRing != null) { GeoAPI.Geometries.ILinearRing shell = ConvertTo(currentExteriorRing); List <GeoAPI.Geometries.ILinearRing> holes = null; //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); IGeometryCollection interiorRingCollection = interiorRings as IGeometryCollection; if (interiorRingCollection != null && interiorRingCollection.GeometryCount > 0) { holes = new List <GeoAPI.Geometries.ILinearRing>(); int interiorRingsTotal = interiorRingCollection.GeometryCount; for (int interiorRingIndex = 0; interiorRingIndex < interiorRingsTotal; interiorRingIndex++) { IRing currentInteriorRing = interiorRingCollection.get_Geometry(interiorRingIndex) as IRing; if (currentInteriorRing != null) { holes.Add(ConvertTo(currentInteriorRing)); } } ////Note we do nothing with the interiorRings, but you can use them the same way as the IGeometryBag exteriorRings //IRing currentInteriorRing = exteriorRingsEnum.Next() as IRing; //while (currentInteriorRing != null) //{ // holes.Add(ConvertTo(currentInteriorRing)); // currentInteriorRing = exteriorRingsEnum.Next() as IRing; //} } GeoAPI.Geometries.IPolygon entry; if (holes != null && holes.Count > 0) { entry = new GisSharpBlog.NetTopologySuite.Geometries.Polygon(shell, holes.ToArray()); } else { entry = new GisSharpBlog.NetTopologySuite.Geometries.Polygon(shell, null); } list.Add(entry); currentExteriorRing = exteriorRingsEnum.Next() as IRing; } if (list != null && list.Count > 0) { output = new GisSharpBlog.NetTopologySuite.Geometries.MultiPolygon(list.ToArray()); } return(output); }
public void SplitPolygons() //分割面 { m_pLineFeed = (INewLineFeedback)m_pFeedback; if (m_pLineFeed == null) { Reset(); return; } IPolyline pFeatureScissors = m_pLineFeed.Stop(); //结束绘制切割线 if (pFeatureScissors.Length == 0) { Reset(); return; } ILayer pFeatureLayer; pFeatureLayer = m_App.CurrentEditLayer; IGeometry pOldGeometry; IFeature pOldFeature; IWorkspaceEdit pWorkspaceEdit; pWorkspaceEdit = (IWorkspaceEdit)CommonFunction.GetLayerWorkspace(pFeatureLayer); if (pWorkspaceEdit == null) { return; } pWorkspaceEdit.StartEditOperation(); for (int i = 0; i < m_OriginFeatureArray.Count; i++) //遍历每个选中的要素 { IArray pArrGeo = new ArrayClass(); pOldFeature = (IFeature)m_OriginFeatureArray.get_Element(i); pOldGeometry = (IGeometry)pOldFeature.Shape; if ((pOldGeometry == null) || (pFeatureScissors == null)) { return; } if (pOldGeometry.GeometryType != esriGeometryType.esriGeometryPolygon) { return; } ITopologicalOperator pTopologim_CalOperator = (ITopologicalOperator)pOldGeometry; IGeometry oRsGeo_1 = null, oRsGeo_2 = null; try { pTopologim_CalOperator.Simplify(); pTopologim_CalOperator.Cut(pFeatureScissors, out oRsGeo_1, out oRsGeo_2); IGeometryCollection oGeoCol = (IGeometryCollection)oRsGeo_1; for (int j = 0; j < oGeoCol.GeometryCount; j++) { ISegmentCollection oNewPoly = new PolygonClass(); oNewPoly.AddSegmentCollection((ISegmentCollection)oGeoCol.get_Geometry(j)); pArrGeo.Add(oNewPoly); } oGeoCol = (IGeometryCollection)oRsGeo_2; for (int j = 0; j < oGeoCol.GeometryCount; j++) { ISegmentCollection oNewPoly = new PolygonClass(); oNewPoly.AddSegmentCollection((ISegmentCollection)oGeoCol.get_Geometry(j)); pArrGeo.Add(oNewPoly); } for (int j = 0; j < pArrGeo.Count; j++) { CommonFunction.AddFeature0(m_MapControl, (IGeometry)pArrGeo.get_Element(j), m_App.CurrentEditLayer, pOldFeature); } pOldFeature.Delete(); } catch { //MessageBox.Show(Ex.ToString()); } } m_App.Workbench.CommandBarManager.Tools["2dmap.DFEditorTool.Undo"].SharedProps.Enabled = true; pWorkspaceEdit.StopEditOperation(); Reset(); }
/// <summary> /// Renders a geometry to the screen depending on the geometry type. /// </summary> /// <param name="g">The graphics object used to draw geometries.</param> /// <param name="map">The map the geometry belongs to and is rendered onto.</param> /// <param name="feature">The feature of which his geometry will be rendered.</param> /// <param name="style">The style to use when rendering the geometry.</param> /// <param name="defaultSymbol">The default symbology to use when none is specified by the style.</param> /// <param name="clippingEnabled">If rendering clipping is enabled.</param> public static void RenderGeometry(Graphics g, IMap map, IGeometry feature, VectorStyle style, Bitmap defaultSymbol, bool clippingEnabled) { Bitmap symbol = style.Symbol; switch (feature.GeometryType) { case "Polygon": if (style.EnableOutline) { DrawPolygon(g, (IPolygon)feature, style.Fill, style.Outline, clippingEnabled, map); } else { DrawPolygon(g, (IPolygon)feature, style.Fill, null, clippingEnabled, map); } break; case "MultiPolygon": if (style.EnableOutline) { DrawMultiPolygon(g, (IMultiPolygon)feature, style.Fill, style.Outline, clippingEnabled, map); } else { DrawMultiPolygon(g, (IMultiPolygon)feature, style.Fill, null, clippingEnabled, map); } break; case "LineString": DrawLineString(g, (ILineString)feature, style.Line, map); break; case "MultiLineString": DrawMultiLineString(g, (IMultiLineString)feature, style.Line, map); break; case "Point": if (symbol == null) { symbol = defaultSymbol; } DrawPoint(g, (IPoint)feature, symbol, style.SymbolScale, style.SymbolOffset, style.SymbolRotation, map); break; case "MultiPoint": if (symbol == null) { symbol = defaultSymbol; } VectorRenderingHelper.DrawMultiPoint(g, (IMultiPoint)feature, symbol, style.SymbolScale, style.SymbolOffset, style.SymbolRotation, map); break; case "GeometryCollection": IGeometryCollection geometryCollection = (IGeometryCollection)feature; for (int i = 0; i < geometryCollection.Count; i++) { RenderGeometry(g, map, geometryCollection[i], style, defaultSymbol, clippingEnabled); } break; default: break; } }
private void SetButton_Click(object obj, EventArgs eventArgs) { int count = this.listJunctionFlag.Count; int count2 = this.listEdgeFlag.Count; int count3 = this.listJunctionBarrier.Count; int count4 = this.listEdgeBarrier.Count; if (count < 1 && count2 < 1) { MessageBox.Show("请用户选择要分析的点或线!"); } else { IEdgeFlag[] array = new EdgeFlag[count2]; IJunctionFlag[] array2 = new JunctionFlag[count]; INetwork network = null; INetworkClass networkClass = null; if (count > 0) { for (int i = 0; i < count; i++) { IFeature feature = this.listJunctionFlag[i]; networkClass = (feature.Class as INetworkClass); network = networkClass.GeometricNetwork.Network; INetElements netElements = network as INetElements; INetFlag netFlag = new JunctionFlag() as INetFlag; ISimpleJunctionFeature simpleJunctionFeature = feature as ISimpleJunctionFeature; int userClassID; int userID; int userSubID; netElements.QueryIDs(simpleJunctionFeature.EID, (esriElementType)1, out userClassID, out userID, out userSubID); netFlag.UserClassID = (userClassID); netFlag.UserID = (userID); netFlag.UserSubID = (userSubID); IJunctionFlag junctionFlag = netFlag as IJunctionFlag; array2[i] = junctionFlag; } } if (count2 > 0) { for (int j = 0; j < count2; j++) { IFeature feature2 = this.listEdgeFlag[j]; networkClass = (feature2.Class as INetworkClass); network = networkClass.GeometricNetwork.Network; INetElements netElements2 = network as INetElements; INetFlag netFlag2 = new EdgeFlag() as INetFlag; ISimpleEdgeFeature simpleEdgeFeature = feature2 as ISimpleEdgeFeature; int userClassID2; int userID2; int userSubID2; netElements2.QueryIDs(simpleEdgeFeature.EID, (esriElementType)2, out userClassID2, out userID2, out userSubID2); netFlag2.UserClassID = (userClassID2); netFlag2.UserID = (userID2); netFlag2.UserSubID = (userSubID2); IEdgeFlag edgeFlag = netFlag2 as IEdgeFlag; array[j] = edgeFlag; } } ITraceFlowSolverGEN traceFlowSolverGEN = new TraceFlowSolver() as ITraceFlowSolverGEN; INetSolver netSolver = traceFlowSolverGEN as INetSolver; INetElementBarriersGEN netElementBarriersGEN = new NetElementBarriers(); netElementBarriersGEN.Network = (network); netElementBarriersGEN.ElementType = (esriElementType)(1); int[] array3 = new int[count3]; int num = 0; if (count3 > 0) { for (int k = 0; k < count3; k++) { IFeature feature3 = this.listJunctionBarrier[k]; networkClass = (feature3.Class as INetworkClass); network = networkClass.GeometricNetwork.Network; INetElements netElements3 = network as INetElements; new EdgeFlag(); ISimpleJunctionFeature simpleJunctionFeature2 = feature3 as ISimpleJunctionFeature; int num2; int num3; netElements3.QueryIDs(simpleJunctionFeature2.EID, (esriElementType)1, out num, out num2, out num3); array3[k] = num2; } netElementBarriersGEN.SetBarriers(num, ref array3); netSolver.set_ElementBarriers((esriElementType)1, (INetElementBarriers)netElementBarriersGEN); } INetElementBarriersGEN netElementBarriersGEN2 = new NetElementBarriers(); netElementBarriersGEN2.Network = (network); netElementBarriersGEN2.ElementType = (esriElementType)(2); int[] array4 = new int[count4]; if (count4 > 0) { for (int l = 0; l < count4; l++) { IFeature feature4 = this.listEdgeBarrier[l]; networkClass = (feature4.Class as INetworkClass); network = networkClass.GeometricNetwork.Network; INetElements netElements4 = network as INetElements; new EdgeFlag(); ISimpleEdgeFeature simpleEdgeFeature2 = feature4 as ISimpleEdgeFeature; int num4; int num5; netElements4.QueryIDs(simpleEdgeFeature2.EID, (esriElementType)2, out num, out num4, out num5); array4[l] = num4; } netElementBarriersGEN2.SetBarriers(num, ref array4); netSolver.set_ElementBarriers((esriElementType)2, (INetElementBarriers)netElementBarriersGEN2); } netSolver.SourceNetwork = (network); if (count > 0) { traceFlowSolverGEN.PutJunctionOrigins(ref array2); } if (count2 > 0) { traceFlowSolverGEN.PutEdgeOrigins(ref array); } IEnumNetEID enumNetEID = null; IEnumNetEID enumNetEID2 = null; object[] array5 = new object[1]; if (this.WayCom.SelectedIndex == 0) { traceFlowSolverGEN.FindSource(0, (esriShortestPathObjFn)1, out enumNetEID, out enumNetEID2, count + count2, ref array5); } if (this.WayCom.SelectedIndex == 1) { traceFlowSolverGEN.FindSource((esriFlowMethod)1, (esriShortestPathObjFn)1, out enumNetEID, out enumNetEID2, count + count2, ref array5); } IPolyline polyline = new Polyline() as IPolyline; IGeometryCollection geometryCollection = polyline as IGeometryCollection; ISpatialReference spatialReference = this.m_iApp.FocusMap.SpatialReference; IEIDHelper iEIDHelper = new EIDHelper(); iEIDHelper.GeometricNetwork = (networkClass.GeometricNetwork); iEIDHelper.OutputSpatialReference = (spatialReference); iEIDHelper.ReturnGeometries = (true); iEIDHelper.ReturnFeatures = (true); int selectedIndex = this.LayerCom.SelectedIndex; if (selectedIndex >= 0 && this.MapControl != null) { this.LayerCom.SelectedItem.ToString(); IFeatureLayer ifeatureLayer_ = ((TrackingAnalyForm.LayerInfo) this.LayerCom.SelectedItem)._layer; if (ifeatureLayer_ != null) { IFeatureSelection featureSelection = (IFeatureSelection)ifeatureLayer_; featureSelection.Clear(); if (enumNetEID2 != null) { IEnumEIDInfo enumEIDInfo = iEIDHelper.CreateEnumEIDInfo(enumNetEID2); int count5 = enumEIDInfo.Count; enumEIDInfo.Reset(); for (int m = 0; m < count5; m++) { IEIDInfo iEIDInfo = enumEIDInfo.Next(); featureSelection.Add(iEIDInfo.Feature); IGeometry geometry = iEIDInfo.Geometry; geometryCollection.AddGeometryCollection(geometry as IGeometryCollection); } } featureSelection.SelectionSet.Refresh(); IActiveView activeView = this.m_iApp.ActiveView; activeView.Refresh(); CMapOperator.ShowFeatureWithWink(this.m_iApp.ActiveView.ScreenDisplay, polyline); } } } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { IGeometry geom = value as IGeometry; if (geom == null) { return; } writer.WriteStartObject(); GeoJsonObjectType geomType = this.ToGeoJsonObject(geom); writer.WritePropertyName("type"); writer.WriteValue(Enum.GetName(typeof(GeoJsonObjectType), geomType)); switch (geomType) { case GeoJsonObjectType.Point: serializer.Serialize(writer, geom.Coordinate); break; case GeoJsonObjectType.LineString: case GeoJsonObjectType.MultiPoint: serializer.Serialize(writer, geom.Coordinates); break; case GeoJsonObjectType.Polygon: IPolygon poly = geom as IPolygon; Debug.Assert(poly != null); serializer.Serialize(writer, PolygonCoordiantes(poly)); break; case GeoJsonObjectType.MultiPolygon: IMultiPolygon mpoly = geom as IMultiPolygon; Debug.Assert(mpoly != null); List <List <Coordinate[]> > list = new List <List <Coordinate[]> >(); foreach (IPolygon mempoly in mpoly.Geometries) { list.Add(PolygonCoordiantes(mempoly)); } serializer.Serialize(writer, list); break; case GeoJsonObjectType.GeometryCollection: IGeometryCollection gc = geom as IGeometryCollection; Debug.Assert(gc != null); serializer.Serialize(writer, gc.Geometries); break; default: List <Coordinate[]> coordinates = new List <Coordinate[]>(); foreach (IGeometry geometry in ((IGeometryCollection)geom).Geometries) { coordinates.Add(geometry.Coordinates); } serializer.Serialize(writer, coordinates); break; } writer.WriteEndObject(); }
/// <summary> /// /// </summary> /// <param name="geometryCollection"></param> /// <param name="writer"></param> protected void Write(IGeometryCollection geometryCollection, XmlTextWriter writer) { writer.WriteStartElement("MultiGeometry", GMLElements.gmlNS); for (int i = 0; i < geometryCollection.NumGeometries; i++) { writer.WriteStartElement("geometryMember", GMLElements.gmlNS); Write(geometryCollection.Geometries[i], writer); writer.WriteEndElement(); } writer.WriteEndElement(); }
/// <summary> /// /// </summary> /// <param name="geometry"></param> /// <returns></returns> protected int SetByteStream(IGeometryCollection geometry) { int count = InitCount; count += 4; foreach (IGeometry geom in geometry.Geometries) count += SetByteStream(geom); return count; }
/// <summary> /// ���ݵ㴴��Ҫ�� /// </summary> /// <params name="pGeom"></params> private void CreateFeature(IGeometry pGeom) { try { if (pGeom == null) return; if (m_pCurrentLayer == null) return; IWorkspaceEdit pWorkspaceEdit = DataEditCommon.g_CurWorkspaceEdit;// GetWorkspaceEdit(); IFeatureLayer pFeatureLayer = (IFeatureLayer)m_pCurrentLayer; IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass; pWorkspaceEdit.StartEditOperation(); IFeature pFeature = pFeatureClass.CreateFeature(); // ����Z/Mֵ DrawCommon.HandleZMValue(pFeature, pGeom, 0); pFeature.Shape = pGeom; pFeature.Store(); pWorkspaceEdit.StopEditOperation(); IActiveView pActiveView = (IActiveView)m_pMap; m_GeometryCollection = null; IGraphicsContainer pGra = m_pMapControl.Map as IGraphicsContainer; for (int i = 0; i < m_ElementArray.Count; i++) { pGra.DeleteElement(m_ElementArray.get_Element(i) as IElement); } m_ElementArray.RemoveAll(); m_pMap.SelectFeature(m_pCurrentLayer, pFeature); m_pMapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics | esriViewDrawPhase.esriViewGeoSelection, null, null); } catch (Exception e) { Console.WriteLine(e.Message.ToString()); } }
/// <summary> /// /// </summary> /// <param name="geomCollection"></param> /// <param name="writer"></param> protected void Write(IGeometryCollection geomCollection, BinaryWriter writer) { WriteHeader(geomCollection, PostGisGeometryType.GeometryCollection, writer); writer.Write((int) geomCollection.NumGeometries); Write(geomCollection.Geometries, writer); }
/// <summary> /// Writes a geometrycollection. /// </summary> /// <param name="gc">The geometrycollection to be written.</param> /// <param name="bWriter">Stream to write to.</param> /// <param name="byteorder">Byte order</param> private static void WriteGeometryCollection(IGeometryCollection gc, BinaryWriter bWriter, WkbByteOrder byteorder) { //Get the number of geometries in this geometrycollection. var num = gc.NumGeometries; //Write the number of geometries. WriteUInt32((uint) num, bWriter, byteorder); //Loop on the number of geometries. //NOTE: by contract, the first item returned // from GetEnumerator (i.e. using foreach) is the IGeometryCollection itself! for (var i = 0; i < num; i++) { IGeometry geom = gc.GetGeometryN(i); //Write the byte-order format of the following geometry. bWriter.Write((byte) byteorder); //Write the type of each geometry. WriteType(geom, bWriter, byteorder); //Write each geometry. WriteGeometry(geom, bWriter, byteorder); } }
public void Write(string filename, IGeometryCollection geometryCollection) { WriteGeometryCollection(filename, geometryCollection); }
/// <summary> /// /// </summary> /// <param name="geomCollection"></param> /// <param name="writer"></param> protected virtual void Write(IGeometryCollection geomCollection, BinaryWriter writer) { WriteByteOrder(writer); writer.Write((int)WkbGeometryType.GeometryCollection); writer.Write(geomCollection.NumGeometries); for (int i = 0; i < geomCollection.NumGeometries; i++) Write(geomCollection.Geometries[i], writer); }
private bool AddEditArea(IServerObject serverObject, string creator, string versionName, int editCount, IEnvelope editZone, bool autoExpandZone = true) { bool isOk = false; IFeatureClass editAreasFC = null; try { // Open edit areas feature class in default workspace editAreasFC = GetEditAreaFeatureClass(serverObject); // Get field indices int creatorFIdx = editAreasFC.FindField(_creatorFName); int creationDateFIdx = editAreasFC.FindField(_creationDateFName); int lastUpdateFIdx = editAreasFC.FindField(_lastUpdateFName); int editCountFIdx = editAreasFC.FindField(_editCountFName); int versionNameFIdx = editAreasFC.FindField(_versionNameFName); DateTime currentTime = DateTime.Now; // Expand zone to make it more visible if (autoExpandZone) { double expandRatio = (editCount <= 3) ? 1.5 : 1.15; editZone.Expand(expandRatio, expandRatio, true); } // Check if there's an existing area IFeature curFeature = null; IFeatureCursor fCursor = GetEditAreas(serverObject, versionName); if (fCursor != null && (curFeature = fCursor.NextFeature()) != null) { // Union the edit zones IPolygon curZone = (IPolygon)curFeature.Shape; IGeometry geometryBag = new GeometryBag(); geometryBag.SpatialReference = curZone.SpatialReference; IGeometryCollection geometryCollection = (IGeometryCollection)geometryBag; geometryCollection.AddGeometry(curZone); geometryCollection.AddGeometry(editZone); Polygon zoneConstructor = new Polygon(); ITopologicalOperator newZone = (ITopologicalOperator)zoneConstructor; newZone.ConstructUnion((IEnumGeometry)geometryCollection); // Update feature values curFeature.Shape = (IGeometry)newZone; curFeature.Value[lastUpdateFIdx] = currentTime; int curCount = (int)curFeature.Value[editCountFIdx]; curFeature.Value[editCountFIdx] = curCount + editCount; // Store feature curFeature.Store(); curFeature = null; } else { // Save edit zone to feature class IFeature zoneFeature = editAreasFC.CreateFeature(); zoneFeature.Value[creatorFIdx] = creator; zoneFeature.Value[creationDateFIdx] = currentTime; zoneFeature.Value[lastUpdateFIdx] = currentTime; zoneFeature.Value[versionNameFIdx] = versionName; zoneFeature.Value[editCountFIdx] = editCount; // Set geometry Polygon editAreaPoly = new Polygon(); ISegmentCollection editAreaSeg = (ISegmentCollection)editAreaPoly; editAreaSeg.SetRectangle(editZone); IZAware polyZAware = editAreaPoly as IZAware; polyZAware.ZAware = false; zoneFeature.Shape = polyZAware as IGeometry; // Store feature zoneFeature.Store(); fCursor.Flush(); fCursor = null; zoneFeature = null; } isOk = true; } catch (Exception e) { _serverLog.LogMessage(ServerLogger.msgType.infoStandard, _soiName + ".AddEditArea()", 200, "Error while adding edit are: " + e.ToString()); } finally { editAreasFC = null; } return(isOk); }
/// <summary> /// /// </summary> /// <param name="collection"></param> /// <param name="operation"></param> /// <returns></returns> private IGeometryCollection EditGeometryCollection(IGeometryCollection collection, GeometryEditorOperation operation) { IGeometryCollection newCollection = (IGeometryCollection) operation.Edit(collection, factory); ArrayList geometries = new ArrayList(); for (int i = 0; i < newCollection.NumGeometries; i++) { IGeometry geometry = Edit(newCollection.GetGeometryN(i), operation); if (geometry.IsEmpty) continue; geometries.Add(geometry); } if (newCollection is IMultiPoint) return factory.CreateMultiPoint((IPoint[]) geometries.ToArray(typeof(IPoint))); if (newCollection is IMultiLineString) return factory.CreateMultiLineString((ILineString[]) geometries.ToArray(typeof(ILineString))); if (newCollection is IMultiPolygon) return factory.CreateMultiPolygon((IPolygon[]) geometries.ToArray(typeof(IPolygon))); return factory.CreateGeometryCollection((IGeometry[]) geometries.ToArray(typeof(IGeometry))); }
public static void CreateVerticalLOSPatches(bool bool_0, IPoint ipoint_0, IPoint ipoint_1, IPolyline ipolyline_0, IPolyline ipolyline_1, IGeometryCollection igeometryCollection_0, IGeometryCollection igeometryCollection_1, out double double_0) { int i; IPointCollection geometry; IClone point; IPointCollection triangleFanClass; IVector3D vector3DClass; IPoint point1; IPoint point2; object value = Missing.Value; IGeometryCollection ipolyline0 = ipolyline_0 as IGeometryCollection; IMultiPatch igeometryCollection1 = igeometryCollection_1 as IMultiPatch; double_0 = ipoint_1.Z; double magnitude = 0; IPoint point3 = null; for (i = 0; i < ipolyline0.GeometryCount; i++) { geometry = ipolyline0.Geometry[i] as IPointCollection; if (i == 0) { point = geometry.Point[0] as IClone; IPoint point4 = point.Clone() as IPoint; } point = geometry as IClone; triangleFanClass = new TriangleFan(); point = ipoint_0 as IClone; triangleFanClass.AddPoint(point.Clone() as IPoint, ref value, ref value); point = geometry as IClone; triangleFanClass.AddPointCollection(point.Clone() as IPointCollection); if (i == ipolyline0.GeometryCount - 1) { vector3DClass = new Vector3D() as IVector3D; point = ipoint_0 as IClone; point1 = point.Clone() as IPoint; point1.Z = 0; point = geometry.Point[geometry.PointCount - 1] as IClone; point2 = point.Clone() as IPoint; point2.Z = 0; vector3DClass.ConstructDifference(point1, point2); magnitude = vector3DClass.Magnitude; point3 = point.Clone() as IPoint; if (ipolyline_1 == null && ipoint_1.Z > geometry.Point[geometry.PointCount - 1].Z) { point = ipoint_1 as IClone; triangleFanClass.AddPoint(point.Clone() as IPoint, ref value, ref value); } } igeometryCollection_0.AddGeometry(triangleFanClass as IGeometry, ref value, ref value); } if (ipolyline_1 != null) { ipolyline0 = ipolyline_1 as IGeometryCollection; for (i = 0; i < ipolyline0.GeometryCount; i++) { geometry = ipolyline0.Geometry[i] as IPointCollection; point = geometry as IClone; IPointCollection ringClass = new Ring(); point = geometry as IClone; ringClass.AddPointCollection(point.Clone() as IPointCollection); if (i == ipolyline0.GeometryCount - 1) { vector3DClass = new Vector3D() as IVector3D; point = ipoint_0 as IClone; point1 = point.Clone() as IPoint; point1.Z = 0; point = geometry.Point[geometry.PointCount - 1] as IClone; point2 = point.Clone() as IPoint; point2.Z = 0; vector3DClass.ConstructDifference(point1, point2); if (magnitude < vector3DClass.Magnitude) { point = ipoint_0 as IClone; point1 = point.Clone() as IPoint; point1.Z = 0; point = geometry.Point[0] as IClone; point2 = point.Clone() as IPoint; point2.Z = 0; vector3DClass.ConstructDifference(point1, point2); double num = vector3DClass.Magnitude; double z = (ipoint_0.Z - geometry.Point[0].Z) / num; point = geometry.Point[geometry.PointCount - 1] as IClone; IPoint z1 = point.Clone() as IPoint; point2 = point.Clone() as IPoint; point2.Z = 0; vector3DClass.ConstructDifference(point1, point2); double magnitude1 = vector3DClass.Magnitude; z1.Z = ipoint_0.Z - magnitude1 * z; point = z1 as IClone; ringClass.AddPoint(point.Clone() as IPoint, ref value, ref value); if (!bool_0) { double_0 = z1.Z; } else { triangleFanClass = new TriangleFan(); point = ipoint_0 as IClone; triangleFanClass.AddPoint(point.Clone() as IPoint, ref value, ref value); point = ipoint_1 as IClone; triangleFanClass.AddPoint(point.Clone() as IPoint, ref value, ref value); point = z1 as IClone; triangleFanClass.AddPoint(point.Clone() as IPoint, ref value, ref value); igeometryCollection_0.AddGeometry(triangleFanClass as IGeometry, ref value, ref value); } } else if (bool_0 && ipoint_1.Z > point3.Z) { triangleFanClass = new TriangleFan(); point = ipoint_0 as IClone; triangleFanClass.AddPoint(point.Clone() as IPoint, ref value, ref value); point = ipoint_1 as IClone; triangleFanClass.AddPoint(point.Clone() as IPoint, ref value, ref value); point = point3 as IClone; triangleFanClass.AddPoint(point.Clone() as IPoint, ref value, ref value); igeometryCollection_0.AddGeometry(triangleFanClass as IGeometry, ref value, ref value); } } point = ringClass.Point[0] as IClone; ringClass.AddPoint(point.Clone() as IPoint, ref value, ref value); igeometryCollection_1.AddGeometry(ringClass as IGeometry, ref value, ref value); igeometryCollection1.PutRingType(ringClass as IRing, esriMultiPatchRingType.esriMultiPatchRing); } } }
/// <summary> /// 完成新建对象,取得绘制的对象,并添加到图层中 /// 建议在Map.DblClick或Map.MouseDown(Button = 2)事件中调用本方法 /// </summary> public void NewFeatureEnd() { IGeometry pGeom = null; IPointCollection pPointCollection; object obj = Type.Missing; try { if (m_pFeedback is INewMultiPointFeedback) { INewMultiPointFeedback pMPFeed = (INewMultiPointFeedback)m_pFeedback; pMPFeed.Stop(); pGeom = (IGeometry)m_pPointCollection; if (m_GeometryCollection == null) { m_GeometryCollection = new PointClass() as IGeometryCollection; } m_GeometryCollection.AddGeometryCollection(pGeom as IGeometryCollection); } else if (m_pFeedback is INewLineFeedback) { INewLineFeedback pLineFeed = (INewLineFeedback)m_pFeedback; if (m_GeometryCollection == null) { m_GeometryCollection = new PolylineClass() as IGeometryCollection; } IPolyline pPolyLine = pLineFeed.Stop(); pPointCollection = (IPointCollection)pPolyLine; if (pPointCollection.PointCount < 2) { MessageBox.Show("至少输入两个节点"); } else { pGeom = (IGeometry)pPointCollection; } m_GeometryCollection.AddGeometryCollection(pGeom as IGeometryCollection); } else if (m_pFeedback is INewPolygonFeedback) { INewPolygonFeedback pPolyFeed = (INewPolygonFeedback)m_pFeedback; if (m_GeometryCollection == null) { m_GeometryCollection = new PolygonClass() as IGeometryCollection; } IPolygon pPolygon; pPolygon = pPolyFeed.Stop(); if (pPolygon != null) { pPointCollection = (IPointCollection)pPolygon; if (pPointCollection.PointCount < 3) { MessageBox.Show("至少输入三个节点"); } else { pGeom = (IGeometry)pPointCollection; } m_GeometryCollection.AddGeometryCollection(pGeom as IGeometryCollection); } } if (pFeatureLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolyline) { IPolyline pline = MyMapHelp.PolygonToPolyline(m_GeometryCollection as IPolygon); CreateFeature(pline as IGeometry); } else { CreateFeature(m_GeometryCollection as IGeometry); } m_pFeedback = null; m_bInUse = false; m_GeometryCollection = null; } catch (Exception e) { m_pFeedback = null; m_bInUse = false; m_GeometryCollection = null; Console.WriteLine(e.Message.ToString()); } }
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { try { IGPUtilities3 execute_Utilities = new GPUtilitiesClass(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter inputFeatureDatasetParameter = paramvalues.get_Element(in_featureDatasetParameterNumber) as IGPParameter; IGPValue inputFeatureDatasetGPValue = execute_Utilities.UnpackGPValue(inputFeatureDatasetParameter); IGPValue outputOSMFileGPValue = execute_Utilities.UnpackGPValue(paramvalues.get_Element(out_osmFileLocationParameterNumber)); // get the name of the feature dataset int fdDemlimiterPosition = inputFeatureDatasetGPValue.GetAsText().LastIndexOf("\\"); string nameOfFeatureDataset = inputFeatureDatasetGPValue.GetAsText().Substring(fdDemlimiterPosition + 1); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; System.Xml.XmlWriter xmlWriter = null; try { xmlWriter = XmlWriter.Create(outputOSMFileGPValue.GetAsText(), settings); } catch (Exception ex) { message.AddError(120021, ex.Message); return; } xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("osm"); // start the osm root node xmlWriter.WriteAttributeString("version", "0.6"); // add the version attribute xmlWriter.WriteAttributeString("generator", "ArcGIS Editor for OpenStreetMap"); // add the generator attribute // write all the nodes // use a feature search cursor to loop through all the known points and write them out as osm node IFeatureClassContainer osmFeatureClasses = execute_Utilities.OpenDataset(inputFeatureDatasetGPValue) as IFeatureClassContainer; if (osmFeatureClasses == null) { message.AddError(120022, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), inputFeatureDatasetParameter.Name)); return; } IFeatureClass osmPointFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_pt"); if (osmPointFeatureClass == null) { message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_pointfeatureclass"), nameOfFeatureDataset + "_osm_pt")); return; } // check the extension of the point feature class to determine its version int internalOSMExtensionVersion = osmPointFeatureClass.OSMExtensionVersion(); IFeatureCursor searchCursor = null; System.Xml.Serialization.XmlSerializerNamespaces xmlnsEmpty = new System.Xml.Serialization.XmlSerializerNamespaces(); xmlnsEmpty.Add("", ""); message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_pts_msg")); int pointCounter = 0; string nodesExportedMessage = String.Empty; // collect the indices for the point feature class once int pointOSMIDFieldIndex = osmPointFeatureClass.Fields.FindField("OSMID"); int pointChangesetFieldIndex = osmPointFeatureClass.Fields.FindField("osmchangeset"); int pointVersionFieldIndex = osmPointFeatureClass.Fields.FindField("osmversion"); int pointUIDFieldIndex = osmPointFeatureClass.Fields.FindField("osmuid"); int pointUserFieldIndex = osmPointFeatureClass.Fields.FindField("osmuser"); int pointTimeStampFieldIndex = osmPointFeatureClass.Fields.FindField("osmtimestamp"); int pointVisibleFieldIndex = osmPointFeatureClass.Fields.FindField("osmvisible"); int pointTagsFieldIndex = osmPointFeatureClass.Fields.FindField("osmTags"); using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = osmPointFeatureClass.Search(null, false); comReleaser.ManageLifetime(searchCursor); System.Xml.Serialization.XmlSerializer pointSerializer = new System.Xml.Serialization.XmlSerializer(typeof(node)); IFeature currentFeature = searchCursor.NextFeature(); IWorkspace pointWorkspace = ((IDataset)osmPointFeatureClass).Workspace; while (currentFeature != null) { if (TrackCancel.Continue() == true) { // convert the found point feature into a osm node representation to store into the OSM XML file node osmNode = ConvertPointFeatureToOSMNode(currentFeature, pointWorkspace, pointTagsFieldIndex, pointOSMIDFieldIndex, pointChangesetFieldIndex, pointVersionFieldIndex, pointUIDFieldIndex, pointUserFieldIndex, pointTimeStampFieldIndex, pointVisibleFieldIndex, internalOSMExtensionVersion); pointSerializer.Serialize(xmlWriter, osmNode, xmlnsEmpty); // increase the point counter to later status report pointCounter++; currentFeature = searchCursor.NextFeature(); } else { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loader so far nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter); message.AddMessage(nodesExportedMessage); return; } } } nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter); message.AddMessage(nodesExportedMessage); // next loop through the line and polygon feature classes to export those features as ways // in case we encounter a multi-part geometry, store it in a relation collection that will be serialized when exporting the relations table IFeatureClass osmLineFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ln"); if (osmLineFeatureClass == null) { message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_linefeatureclass"), nameOfFeatureDataset + "_osm_ln")); return; } message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_ways_msg")); // as we are looping through the line and polygon feature classes let's collect the multi-part features separately // as they are considered relations in the OSM world List<relation> multiPartElements = new List<relation>(); System.Xml.Serialization.XmlSerializer waySerializer = new System.Xml.Serialization.XmlSerializer(typeof(way)); int lineCounter = 0; int relationCounter = 0; string waysExportedMessage = String.Empty; using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = osmLineFeatureClass.Search(null, false); comReleaser.ManageLifetime(searchCursor); IFeature currentFeature = searchCursor.NextFeature(); // collect the indices for the point feature class once int lineOSMIDFieldIndex = osmLineFeatureClass.Fields.FindField("OSMID"); int lineChangesetFieldIndex = osmLineFeatureClass.Fields.FindField("osmchangeset"); int lineVersionFieldIndex = osmLineFeatureClass.Fields.FindField("osmversion"); int lineUIDFieldIndex = osmLineFeatureClass.Fields.FindField("osmuid"); int lineUserFieldIndex = osmLineFeatureClass.Fields.FindField("osmuser"); int lineTimeStampFieldIndex = osmLineFeatureClass.Fields.FindField("osmtimestamp"); int lineVisibleFieldIndex = osmLineFeatureClass.Fields.FindField("osmvisible"); int lineTagsFieldIndex = osmLineFeatureClass.Fields.FindField("osmTags"); int lineMembersFieldIndex = osmLineFeatureClass.Fields.FindField("osmMembers"); IWorkspace lineWorkspace = ((IDataset)osmLineFeatureClass).Workspace; while (currentFeature != null) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter); message.AddMessage(waysExportedMessage); return; } //test if the feature geometry has multiple parts IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection; if (geometryCollection != null) { if (geometryCollection.GeometryCount == 1) { // convert the found polyline feature into a osm way representation to store into the OSM XML file way osmWay = ConvertFeatureToOSMWay(currentFeature, lineWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, internalOSMExtensionVersion); waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty); // increase the line counter for later status report lineCounter++; } else { relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, lineWorkspace, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, lineMembersFieldIndex, internalOSMExtensionVersion); multiPartElements.Add(osmRelation); // increase the line counter for later status report relationCounter++; } } currentFeature = searchCursor.NextFeature(); } } IFeatureClass osmPolygonFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ply"); IFeatureWorkspace commonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace as IFeatureWorkspace; if (osmPolygonFeatureClass == null) { message.AddError(120024, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_polygonfeatureclass"), nameOfFeatureDataset + "_osm_ply")); return; } using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = osmPolygonFeatureClass.Search(null, false); comReleaser.ManageLifetime(searchCursor); IFeature currentFeature = searchCursor.NextFeature(); // collect the indices for the point feature class once int polygonOSMIDFieldIndex = osmPolygonFeatureClass.Fields.FindField("OSMID"); int polygonChangesetFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmchangeset"); int polygonVersionFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmversion"); int polygonUIDFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmuid"); int polygonUserFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmuser"); int polygonTimeStampFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmtimestamp"); int polygonVisibleFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmvisible"); int polygonTagsFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmTags"); int polygonMembersFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmMembers"); IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace; while (currentFeature != null) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter); message.AddMessage(waysExportedMessage); message.AddAbort(resourceManager.GetString("GPTools_toolabort")); return; } //test if the feature geometry has multiple parts IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection; if (geometryCollection != null) { if (geometryCollection.GeometryCount == 1) { // convert the found polyline feature into a osm way representation to store into the OSM XML file way osmWay = ConvertFeatureToOSMWay(currentFeature, polygonWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, internalOSMExtensionVersion); waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty); // increase the line counter for later status report lineCounter++; } else { relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, polygonWorkspace, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, polygonMembersFieldIndex, internalOSMExtensionVersion); multiPartElements.Add(osmRelation); // increase the line counter for later status report relationCounter++; } } currentFeature = searchCursor.NextFeature(); } } waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter); message.AddMessage(waysExportedMessage); // now let's go through the relation table message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_relations_msg")); ITable relationTable = commonWorkspace.OpenTable(nameOfFeatureDataset + "_osm_relation"); if (relationTable == null) { message.AddError(120025, String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_relationTable"), nameOfFeatureDataset + "_osm_relation")); return; } System.Xml.Serialization.XmlSerializer relationSerializer = new System.Xml.Serialization.XmlSerializer(typeof(relation)); string relationsExportedMessage = String.Empty; using (ComReleaser comReleaser = new ComReleaser()) { ICursor rowCursor = relationTable.Search(null, false); comReleaser.ManageLifetime(rowCursor); IRow currentRow = rowCursor.NextRow(); // collect the indices for the relation table once int relationOSMIDFieldIndex = relationTable.Fields.FindField("OSMID"); int relationChangesetFieldIndex = relationTable.Fields.FindField("osmchangeset"); int relationVersionFieldIndex = relationTable.Fields.FindField("osmversion"); int relationUIDFieldIndex = relationTable.Fields.FindField("osmuid"); int relationUserFieldIndex = relationTable.Fields.FindField("osmuser"); int relationTimeStampFieldIndex = relationTable.Fields.FindField("osmtimestamp"); int relationVisibleFieldIndex = relationTable.Fields.FindField("osmvisible"); int relationTagsFieldIndex = relationTable.Fields.FindField("osmTags"); int relationMembersFieldIndex = relationTable.Fields.FindField("osmMembers"); IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace; while (currentRow != null) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter); message.AddMessage(relationsExportedMessage); message.AddAbort(resourceManager.GetString("GPTools_toolabort")); return; } relation osmRelation = ConvertRowToOSMRelation(currentRow, (IWorkspace)commonWorkspace, relationTagsFieldIndex, relationOSMIDFieldIndex, relationChangesetFieldIndex, relationVersionFieldIndex, relationUIDFieldIndex, relationUserFieldIndex, relationTimeStampFieldIndex, relationVisibleFieldIndex, relationMembersFieldIndex, internalOSMExtensionVersion); relationSerializer.Serialize(xmlWriter, osmRelation, xmlnsEmpty); // increase the line counter for later status report relationCounter++; currentRow = rowCursor.NextRow(); } } // lastly let's serialize the collected multipart-geometries back into relation elements foreach (relation currentRelation in multiPartElements) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter); message.AddMessage(relationsExportedMessage); return; } relationSerializer.Serialize(xmlWriter, currentRelation, xmlnsEmpty); relationCounter++; } relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter); message.AddMessage(relationsExportedMessage); xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document } catch (Exception ex) { message.AddError(11111, ex.StackTrace); message.AddError(120026, ex.Message); } }
/// <summary> /// /// </summary> /// <param name="geometryCollection"></param> /// <returns></returns> protected int SetByteStreamLength(IGeometryCollection geometryCollection) { int count = InitValue; foreach (IGeometry g in geometryCollection.Geometries) count += SetByteStreamLength(g); return count; }
public static void ShowAllVertex(IFeatureLayer pFeatLyr) { m_vertexGeoBag = null; if (pFeatLyr == null) { return; } IFeatureCursor pFeatureCursor = MapManager.GetSelectedFeatures(pFeatLyr); if (pFeatureCursor == null) { return; } IFeature pTFeature = null; //得到要显示节点的地物 pTFeature = pFeatureCursor.NextFeature(); if (pTFeature == null) { return; } //只选中一个地物进行节点移动 m_Map.ClearSelection(); m_Map.SelectFeature(pFeatLyr as ILayer, pTFeature); m_activeView.Refresh(); //如果为点状地物,不显示节点 if (pTFeature.Shape.GeometryType == esriGeometryType.esriGeometryPoint) { return; } IArray pFeatureArray = null; pFeatureArray = new ESRI.ArcGIS.esriSystem.Array(); pFeatureArray.Add(pTFeature); //绘图符号初始化 SymbolInit(); IFeature pFeature = default(IFeature); IPointCollection pPointCol = default(IPointCollection); IPoint pPoint = default(IPoint); int i = 0; int j = 0; m_vertexGeoBag = new GeometryBagClass(); for (i = 0; i <= pFeatureArray.Count - 1; i++) { pFeature = pFeatureArray.get_Element(i) as IFeature; //获取图形边界的点集 pPointCol = pFeature.ShapeCopy as IPointCollection; for (j = 0; j <= pPointCol.PointCount - 1; j++) { pPoint = pPointCol.get_Point(j); if (j == 0 | j == pPointCol.PointCount - 1) { //两个端点的ID设为10 pPoint.ID = 10; } else { //中间点的ID设为100 pPoint.ID = 100; } IColor pColor = null; object obj = Type.Missing; //显示节点 if (pPoint == pHitPnt) { DisplayGraphic(pPoint, pColor, m_selPointSym as ISymbol); } if (j == 0 || j == pPointCol.PointCount - 1) { DisplayGraphic(pPoint, pColor, m_endPointSym as ISymbol); } else { DisplayGraphic(pPoint, pColor, m_vertexSym as ISymbol); } m_vertexGeoBag.AddGeometry(pPoint, ref obj, ref obj); } } }
/// <summary> /// /// </summary> /// <param name="geomCollection"></param> /// <param name="writer"></param> protected void Write(IGeometryCollection geomCollection, BinaryWriter writer) { WriteByteOrder(writer); // LittleIndian writer.Write((int)WKBGeometryTypes.WKBGeometryCollection); writer.Write((int)geomCollection.NumGeometries); for (int i = 0; i < geomCollection.NumGeometries; i++) Write(geomCollection.Geometries[i], writer); ; }
public static IGeometry GetExample1() { //Composite: Multiple, Disjoint Geometries Contained Within A Single MultiPatch IGeometryCollection multiPatchGeometryCollection = new MultiPatchClass(); IMultiPatch multiPatch = multiPatchGeometryCollection as IMultiPatch; //Vector3D Example 2 IGeometry vector3DExample2Geometry = Vector3DExamples.GetExample2(); ITransform3D vector3DExample2Transform3D = vector3DExample2Geometry as ITransform3D; vector3DExample2Transform3D.Move3D(5, 5, 0); IGeometryCollection vector3DExample2GeometryCollection = vector3DExample2Geometry as IGeometryCollection; for (int i = 0; i < vector3DExample2GeometryCollection.GeometryCount; i++) { multiPatchGeometryCollection.AddGeometry(vector3DExample2GeometryCollection.get_Geometry(i), ref _missing, ref _missing); } //Vector3D Example 3 IGeometry vector3DExample3Geometry = Vector3DExamples.GetExample3(); ITransform3D vector3DExample3Transform3D = vector3DExample3Geometry as ITransform3D; vector3DExample3Transform3D.Move3D(5, -5, 0); IGeometryCollection vector3DExample3GeometryCollection = vector3DExample3Geometry as IGeometryCollection; for (int i = 0; i < vector3DExample3GeometryCollection.GeometryCount; i++) { multiPatchGeometryCollection.AddGeometry(vector3DExample3GeometryCollection.get_Geometry(i), ref _missing, ref _missing); } //Vector3D Example 4 IGeometry vector3DExample4Geometry = Vector3DExamples.GetExample4(); ITransform3D vector3DExample4Transform3D = vector3DExample4Geometry as ITransform3D; vector3DExample4Transform3D.Move3D(-5, -5, 0); IGeometryCollection vector3DExample4GeometryCollection = vector3DExample4Geometry as IGeometryCollection; for (int i = 0; i < vector3DExample4GeometryCollection.GeometryCount; i++) { multiPatchGeometryCollection.AddGeometry(vector3DExample4GeometryCollection.get_Geometry(i), ref _missing, ref _missing); } //Vector3D Example 5 IGeometry vector3DExample5Geometry = Vector3DExamples.GetExample5(); ITransform3D vector3DExample5Transform3D = vector3DExample5Geometry as ITransform3D; vector3DExample5Transform3D.Move3D(-5, 5, 0); IGeometryCollection vector3DExample5GeometryCollection = vector3DExample5Geometry as IGeometryCollection; for (int i = 0; i < vector3DExample5GeometryCollection.GeometryCount; i++) { multiPatchGeometryCollection.AddGeometry(vector3DExample5GeometryCollection.get_Geometry(i), ref _missing, ref _missing); } return(multiPatchGeometryCollection as IGeometry); }
/// <summary> /// /// </summary> /// <param name="geometry"></param> /// <returns></returns> protected int SetByteStream(IGeometryCollection geometry) { // 4-byte count + subgeometries return 4 + SetByteStream(geometry.Geometries); }
public static IGeometry GetExample4() { const double CircleDegrees = 360.0; const int CircleDivisions = 18; const double VectorComponentOffset = 0.0000001; const double InnerBuildingRadius = 3.0; const double OuterBuildingExteriorRingRadius = 9.0; const double OuterBuildingInteriorRingRadius = 6.0; const double BaseZ = 0.0; const double InnerBuildingZ = 16.0; const double OuterBuildingZ = 6.0; //Composite: Tall Building Protruding Through Outer Ring-Shaped Building IMultiPatch multiPatch = new MultiPatchClass(); IGeometryCollection multiPatchGeometryCollection = multiPatch as IGeometryCollection; IPoint originPoint = GeometryUtilities.ConstructPoint3D(0, 0, 0); IVector3D upperAxisVector3D = GeometryUtilities.ConstructVector3D(0, 0, 10); IVector3D lowerAxisVector3D = GeometryUtilities.ConstructVector3D(0, 0, -10); lowerAxisVector3D.XComponent += VectorComponentOffset; IVector3D normalVector3D = upperAxisVector3D.CrossProduct(lowerAxisVector3D) as IVector3D; double rotationAngleInRadians = GeometryUtilities.GetRadians(CircleDegrees / CircleDivisions); //Inner Building IGeometry innerBuildingBaseGeometry = new PolygonClass(); IPointCollection innerBuildingBasePointCollection = innerBuildingBaseGeometry as IPointCollection; //Outer Building IGeometry outerBuildingBaseGeometry = new PolygonClass(); IGeometryCollection outerBuildingBaseGeometryCollection = outerBuildingBaseGeometry as IGeometryCollection; IPointCollection outerBuildingBaseExteriorRingPointCollection = new RingClass(); IPointCollection outerBuildingBaseInteriorRingPointCollection = new RingClass(); for (int i = 0; i < CircleDivisions; i++) { normalVector3D.Rotate(-1 * rotationAngleInRadians, upperAxisVector3D); //Inner Building normalVector3D.Magnitude = InnerBuildingRadius; IPoint innerBuildingBaseVertexPoint = GeometryUtilities.ConstructPoint2D(originPoint.X + normalVector3D.XComponent, originPoint.Y + normalVector3D.YComponent); innerBuildingBasePointCollection.AddPoint(innerBuildingBaseVertexPoint, ref _missing, ref _missing); //Outer Building //Exterior Ring normalVector3D.Magnitude = OuterBuildingExteriorRingRadius; IPoint outerBuildingBaseExteriorRingVertexPoint = GeometryUtilities.ConstructPoint2D(originPoint.X + normalVector3D.XComponent, originPoint.Y + normalVector3D.YComponent); outerBuildingBaseExteriorRingPointCollection.AddPoint(outerBuildingBaseExteriorRingVertexPoint, ref _missing, ref _missing); //Interior Ring normalVector3D.Magnitude = OuterBuildingInteriorRingRadius; IPoint outerBuildingBaseInteriorRingVertexPoint = GeometryUtilities.ConstructPoint2D(originPoint.X + normalVector3D.XComponent, originPoint.Y + normalVector3D.YComponent); outerBuildingBaseInteriorRingPointCollection.AddPoint(outerBuildingBaseInteriorRingVertexPoint, ref _missing, ref _missing); } IPolygon innerBuildingBasePolygon = innerBuildingBaseGeometry as IPolygon; innerBuildingBasePolygon.Close(); IRing outerBuildingBaseExteriorRing = outerBuildingBaseExteriorRingPointCollection as IRing; outerBuildingBaseExteriorRing.Close(); IRing outerBuildingBaseInteriorRing = outerBuildingBaseInteriorRingPointCollection as IRing; outerBuildingBaseInteriorRing.Close(); outerBuildingBaseInteriorRing.ReverseOrientation(); outerBuildingBaseGeometryCollection.AddGeometry(outerBuildingBaseExteriorRing as IGeometry, ref _missing, ref _missing); outerBuildingBaseGeometryCollection.AddGeometry(outerBuildingBaseInteriorRing as IGeometry, ref _missing, ref _missing); ITopologicalOperator topologicalOperator = outerBuildingBaseGeometry as ITopologicalOperator; topologicalOperator.Simplify(); IConstructMultiPatch innerBuildingConstructMultiPatch = new MultiPatchClass(); innerBuildingConstructMultiPatch.ConstructExtrudeFromTo(BaseZ, InnerBuildingZ, innerBuildingBaseGeometry); IGeometryCollection innerBuildingMultiPatchGeometryCollection = innerBuildingConstructMultiPatch as IGeometryCollection; for (int i = 0; i < innerBuildingMultiPatchGeometryCollection.GeometryCount; i++) { multiPatchGeometryCollection.AddGeometry(innerBuildingMultiPatchGeometryCollection.get_Geometry(i), ref _missing, ref _missing); } IConstructMultiPatch outerBuildingConstructMultiPatch = new MultiPatchClass(); outerBuildingConstructMultiPatch.ConstructExtrudeFromTo(BaseZ, OuterBuildingZ, outerBuildingBaseGeometry); IMultiPatch outerBuildingMultiPatch = outerBuildingConstructMultiPatch as IMultiPatch; IGeometryCollection outerBuildingMultiPatchGeometryCollection = outerBuildingConstructMultiPatch as IGeometryCollection; for (int i = 0; i < outerBuildingMultiPatchGeometryCollection.GeometryCount; i++) { IGeometry outerBuildingPatchGeometry = outerBuildingMultiPatchGeometryCollection.get_Geometry(i); multiPatchGeometryCollection.AddGeometry(outerBuildingPatchGeometry, ref _missing, ref _missing); if (outerBuildingPatchGeometry.GeometryType == esriGeometryType.esriGeometryRing) { bool isBeginningRing = false; esriMultiPatchRingType multiPatchRingType = outerBuildingMultiPatch.GetRingType(outerBuildingPatchGeometry as IRing, ref isBeginningRing); multiPatch.PutRingType(outerBuildingPatchGeometry as IRing, multiPatchRingType); } } return(multiPatchGeometryCollection as IGeometry); }
/// <summary> /// Method to write a collection of geometries to a shapefile on disk. /// </summary> /// <remarks> /// Assumes the type given for the first geometry is the same for all subsequent geometries. /// For example, is, if the first Geometry is a Multi-polygon/ Polygon, the subsequent geometies are /// Muli-polygon/ polygon and not lines or points. /// The dbase file for the corresponding shapefile contains one column called row. It contains /// the row number. /// </remarks> /// <param name="filename">The filename to write to (minus the .shp extension).</param> /// <param name="geometryCollection">The GeometryCollection to write.</param> public static void WriteGeometryCollection(string filename, IGeometryCollection geometryCollection) { var shapeFileType = Shapefile.GetShapeType(geometryCollection); var numShapes = geometryCollection.NumGeometries; using (var writer = new ShapefileWriter(geometryCollection.Factory, filename, shapeFileType)) { for (var i = 0; i < numShapes; i++) { writer.Write(geometryCollection[i]); } } WriteDummyDbf(filename + ".dbf", numShapes); }
private void btnOK_Click(object sender, EventArgs e) { IFeature pAttributeFeature = default(IFeature); ISubtypes pSubtypes = default(ISubtypes); ArrayList colAttributes = null; IFeature pCurFeature = default(IFeature); IFeature pNewFeature = default(IFeature); IGeometry pCurGeom = default(IGeometry); IGeometry pTmpGeom = default(IGeometry); ITopologicalOperator5 pTopoOperator = default(ITopologicalOperator5); IRowSubtypes pOutRSType = default(IRowSubtypes); IFields pFlds = default(IFields); IField pFld = default(IField); IDomain pDomain = default(IDomain); IGeometryCollection pGeomColl = default(IGeometryCollection); IInvalidArea pRefresh = null; IComplexEdgeFeature pCEF = null; IMap pMap = null; try { long lGTotalVal = 0; int lSubTypeCode = 0; string strOID = null; int intOID = -1; int i, j; //Screen.MousePointer = vbHourglass //The Next button doesn't get enabled until at least 1 FC is selected, but just in case... if (lstMergeFeatures.Items.Count == 0) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("SlctOneFtr")); return; } //For Next loop which iterates through the array populating colSelClasses //This is for when I implement selecting multiple feature classes from the listbox.... for (i = 0; i <= lstMergeFeatures.Items.Count - 1; i++) { if (lstMergeFeatures.Items[i].Selected) { strOID = lstMergeFeatures.Items[i].Text; intOID = Convert.ToInt32(strOID); break; // TODO: might not be correct. Was : Exit For } } if (strOID == null) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("SlctMainFtr")); return; } //Get the field values of the selected feature for use later pAttributeFeature = (IFeature)m_colFeatures[strOID]; colAttributes = new ArrayList(); for (i = 0; i < pAttributeFeature.Fields.FieldCount; i++) { colAttributes.Add(pAttributeFeature.get_Value(i).ToString()); } pSubtypes = (ISubtypes)m_FeatLay.FeatureClass; if (pSubtypes.HasSubtype) { lSubTypeCode = (int)pAttributeFeature.get_Value(pSubtypes.SubtypeFieldIndex); } else { lSubTypeCode = 0; } //If the features being merged and the target layer are the same FC and if that FC has subtypes, get the subtype code of the selected feature or target layer //If not, get the default //pSubtypes = m_pFC; //if pSubtypes.HasSubtype Then // lSubTypeCode = m_lSubtype //End If //start edit operation m_editor.StartOperation(); //pEnumFeature = m_pEditor.EditSelection //pEnumFeature.Reset //create a new feature to be the merge feature //pNFC = m_pFC 'QI //Create the new feature pNewFeature = m_FeatLay.FeatureClass.CreateFeature(); //create the new geometry. //initialize the default values for the new feature pOutRSType = (IRowSubtypes)pNewFeature; //Set the RowSubtypes to the NewFeature //if (lSubTypeCode <> 0 ) pOutRSType.SubtypeCode = lSubTypeCode; //If there's a subtype code, set it //End If pOutRSType.InitDefaultValues(); //Init the Default values for the feature pFlds = m_FeatLay.FeatureClass.Fields; //Loop until we've gone through all the selected features (pCurFeature) i = 0; IList <MergeSplitFlds> pFldsNames = new List <MergeSplitFlds>(); if (m_Config != null) { if (m_Config.Count > 0) { if (m_Config[0] != null) { if (m_Config[0].Fields != null) { foreach (A4LGSharedFunctions.Field FldNam in m_Config[0].Fields) { int idx = Globals.GetFieldIndex(pFlds, FldNam.Name); if (idx > -1) { try { pFldsNames.Add(new MergeSplitFlds(FldNam.Name, idx, "", FldNam.MergeRule, FldNam.SplitRule)); } catch { } } } } } } } foreach (string ky in m_colFeatures.Keys) { //} //for (i = 0; i < m_colFeatures.Count; i++) //{ pCurFeature = (IFeature)m_colFeatures[ky]; if (pFldsNames != null) { foreach (MergeSplitFlds FldNam in pFldsNames) { string testVal = pCurFeature.get_Value(FldNam.FieldIndex).ToString(); //if (Globals.IsNumeric(testVal)) //{ // FldNam.Value = FldNam.Value + Convert.ToDouble(testVal); //} switch (FldNam.MergeType.ToUpper()) { case "MAX": if (FldNam.Value == "") { FldNam.Value = testVal; } else { if (Convert.ToDouble(FldNam.Value) < Convert.ToDouble(testVal)) { FldNam.Value = testVal; } } break; case "MIN": if (FldNam.Value == "") { FldNam.Value = testVal; } else { if (Convert.ToDouble(FldNam.Value) > Convert.ToDouble(testVal)) { FldNam.Value = testVal; } } break; case "SUM": if (FldNam.Value == "") { FldNam.Value = testVal; } else { FldNam.Value += Convert.ToDouble(FldNam.Value) + Convert.ToDouble(testVal); } break; case "AVERAGE": if (FldNam.Value == "") { FldNam.Value = testVal; } else { FldNam.Value += Convert.ToDouble(FldNam.Value) + Convert.ToDouble(testVal); } FldNam.AvgCount++; break; case "CONCAT": if (FldNam.Value.Contains(testVal.ToString() + ConcatDelim)) { } else if (FldNam.Value.Contains(ConcatDelim + testVal.ToString())) { } else { if (FldNam.Value == "") { FldNam.Value = testVal.ToString(); } else { FldNam.Value += ConcatDelim + testVal.ToString(); } } break; default: break; } } } //get the geometry of the current feature, if it's the first feature, set it to pTmpGeom //Otherwise, pTmpGeom is already set so Union the Geom of this feature with pTmpGeom //And set that equal to the new pTmpGeom...... pCurGeom = pCurFeature.ShapeCopy; if (i == 0) { pTmpGeom = pCurGeom; pTopoOperator = (ESRI.ArcGIS.Geometry.ITopologicalOperator5)pTmpGeom; pTopoOperator.IsKnownSimple_2 = false; //051710 pTopoOperator.Simplify(); // 051710 } else { //Simplify the just obtained OtherPolyLine pTopoOperator = (ESRI.ArcGIS.Geometry.ITopologicalOperator5)pCurGeom;//051710 pTopoOperator.IsKnownSimple_2 = false; pTopoOperator.Simplify(); //Reset the pTopoOp to pNewPolyLine in prep for the union pTopoOperator = (ESRI.ArcGIS.Geometry.ITopologicalOperator5)pTmpGeom; pTmpGeom = pTopoOperator.Union(pCurGeom); //Simplify the resulting New Line pTopoOperator = (ESRI.ArcGIS.Geometry.ITopologicalOperator5)pTmpGeom; pTopoOperator.IsKnownSimple_2 = false; pTopoOperator.Simplify(); //pTopoOperator = (ITopologicalOperator5)pTmpGeom; //pTopoOperator.Simplify(); //pOutputGeometry = pTopoOperator.Union(pCurGeom); //pTopoOperator.Simplify(); //pTmpGeom = pOutputGeometry; //pTopoOperator.SimplifyAsFeature(); //pOutputGeometry = pTopoOperator.UnionEx(pCurGeom,true); //pTopoOperator.SimplifyAsFeature(); //pTmpGeom = pOutputGeometry; //pTopoOperator.Simplify(); //pOutputGeometry = pTopoOperator.Union(pCurGeom); //pTmpGeom = pOutputGeometry; } //now go through each field, if it has a domain associated with it, then evaluate the merge policy... //If not domain, then grab the value from the selected feature for (j = 0; j < pFlds.FieldCount; j++) { pFld = pFlds.get_Field(j); pDomain = pSubtypes.get_Domain(lSubTypeCode, pFld.Name); if (pDomain != null && pFld.DefaultValue != null) { if (pDomain.MergePolicy == esriMergePolicyType.esriMPTSumValues) { //if (lCount == 1) // pNewFeature.set_Value(j, pCurFeature.get_Value(j)); //else if (pNewFeature.get_Value(j) != null && pCurFeature.get_Value(j) != null) { if (Globals.IsNumeric(pNewFeature.get_Value(j).ToString()) && Globals.IsNumeric(pCurFeature.get_Value(j).ToString())) { pNewFeature.set_Value(j, (double)pNewFeature.get_Value(j) + (double)pCurFeature.get_Value(j)); } else if (Globals.IsNumeric(pNewFeature.get_Value(j).ToString())) { pNewFeature.set_Value(j, (double)pNewFeature.get_Value(j)); } else if (Globals.IsNumeric(pCurFeature.get_Value(j).ToString())) { pNewFeature.set_Value(j, (double)pCurFeature.get_Value(j)); } } else if (pNewFeature.get_Value(j) != null) { if (Globals.IsNumeric(pNewFeature.get_Value(j).ToString())) { pNewFeature.set_Value(j, (double)pNewFeature.get_Value(j)); } } else if (pCurFeature.get_Value(j) != null) { if (Globals.IsNumeric(pCurFeature.get_Value(j).ToString())) { pNewFeature.set_Value(j, (double)pCurFeature.get_Value(j)); } } else { } } else if (pDomain.MergePolicy == esriMergePolicyType.esriMPTAreaWeighted) { if (pNewFeature.get_Value(j) != null && pCurFeature.get_Value(j) != null) { if (Globals.IsNumeric(pNewFeature.get_Value(j).ToString()) && Globals.IsNumeric(pCurFeature.get_Value(j).ToString())) { pNewFeature.set_Value(j, (Double)pNewFeature.get_Value(j) + ((Double)pCurFeature.get_Value(j) * (Globals.GetGeometryLength(pCurFeature) / lGTotalVal))); } else if (Globals.IsNumeric(pNewFeature.get_Value(j).ToString())) { pNewFeature.set_Value(j, (Double)pNewFeature.get_Value(j) * (Globals.GetGeometryLength(pCurFeature) / lGTotalVal)); } else if (Globals.IsNumeric(pCurFeature.get_Value(j).ToString())) { pNewFeature.set_Value(j, (Double)pCurFeature.get_Value(j) * (Globals.GetGeometryLength(pCurFeature) / lGTotalVal)); } } else if (pNewFeature.get_Value(j) != null) { if (Globals.IsNumeric(pNewFeature.get_Value(j).ToString())) { pNewFeature.set_Value(j, (Double)pNewFeature.get_Value(j) * (Globals.GetGeometryLength(pCurFeature) / lGTotalVal)); } } else if (pCurFeature.get_Value(j) != null) { if (Globals.IsNumeric(pCurFeature.get_Value(j).ToString())) { pNewFeature.set_Value(j, (Double)pCurFeature.get_Value(j) * (Globals.GetGeometryLength(pCurFeature) / lGTotalVal)); } } else { } } else if (pCurFeature.OID == pAttributeFeature.OID) { try { pNewFeature.set_Value(j, pCurFeature.get_Value(j)); } catch { } } } else if (pCurFeature.OID == intOID) { //Set the field values from the selected feature; ignore Subtype, non-editable and Shape field if (pFld.Editable == true && pSubtypes.SubtypeFieldIndex != j && m_FeatLay.FeatureClass.ShapeFieldName.ToUpper() != pFld.Name.ToUpper()) { //if (colAttributes[j] != null) //{ try { pNewFeature.set_Value(j, colAttributes[j]); } catch { } // } } } } pCurFeature.Delete(); //delete the feature i++; } //Check if the merged geometry is multi-part. If so, raise an error and abort //Multipart geometries are not supported in the geometric network. pGeomColl = (IGeometryCollection)pTmpGeom; if (pGeomColl.GeometryCount > 1) { m_editor.AbortOperation(); MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("SlctOneFtr"), A4LGSharedFunctions.Localizer.GetString("ErrorOn") + A4LGSharedFunctions.Localizer.GetString("MergeOprt_4")); this.Close(); return; } pNewFeature.Shape = pTmpGeom; pNewFeature.Store(); if (m_FeatLay.FeatureClass.FeatureType == esriFeatureType.esriFTComplexEdge) { pCEF = (IComplexEdgeFeature)pNewFeature; pCEF.ConnectAtIntermediateVertices(); } if (chkMergeElevationData.Checked) { if (pFldsNames != null) { foreach (MergeSplitFlds FldNam in pFldsNames) { if (FldNam.MergeType.ToUpper() == "Average".ToUpper()) { FldNam.Value = (Convert.ToDouble(FldNam.Value) / FldNam.AvgCount).ToString(); } try { pNewFeature.set_Value(FldNam.FieldIndex, FldNam.Value); } catch { } } } } //finish edit operation m_editor.StopOperation(A4LGSharedFunctions.Localizer.GetString("MergeOprt_4")); //refresh features pRefresh = new InvalidArea(); pRefresh.Display = m_editor.Display; pRefresh.Add(pNewFeature); pRefresh.Invalidate(-2); // 'select new feature pMap = m_editor.Map; pMap.ClearSelection(); pMap.SelectFeature((ILayer)m_FeatLay, pNewFeature); this.Close(); } catch (Exception ex) { if (ex.ToString().ToString().Contains("Key cannot be null")) { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorOn") + A4LGSharedFunctions.Localizer.GetString("MergeOprt_5") + "\r\n" + A4LGSharedFunctions.Localizer.GetString("MergeOprt_6")); } else { MessageBox.Show(A4LGSharedFunctions.Localizer.GetString("ErrorOn") + A4LGSharedFunctions.Localizer.GetString("MergeOprt_5") + "\r\n" + ex.ToString()); } try { //finish edit operation m_editor.StopOperation(A4LGSharedFunctions.Localizer.GetString("MergeOprt_4")); } catch { } this.Close(); } finally { pAttributeFeature = null; pSubtypes = null; colAttributes = null; pCurFeature = null; pNewFeature = null; pCurGeom = null; pTmpGeom = null; pTopoOperator = null; pOutRSType = null; pFlds = null; pFld = null; pDomain = null; pGeomColl = null; pRefresh = null; pCEF = null; pMap = null; } }