Example #1
1
        /// <summary>
        /// 
        /// </summary>
        /// <param name="polygon"></param>
        /// <param name="writer"></param>
        public void Write(IPolygon polygon, BinaryWriter writer)
        {
            writer.Write((int) ShapeGeometryTypes.Polygon);

            // Write BoundingBox            
            WriteBoundingBox(polygon, writer);

            // Write NumParts and NumPoints            
            writer.Write((int) (polygon.NumInteriorRings + 1));
            writer.Write((int)  polygon.NumPoints);

            // Write IndexParts
            int count = 0;
            writer.Write((int) count);
            if (polygon.NumInteriorRings != 0)
            {
                // Write external shell index
                count += polygon.ExteriorRing.NumPoints;
                writer.Write((int) count);
                for (int i = 1; i < polygon.NumInteriorRings; i++)
                {
                    // Write internal holes index
                    count += polygon.GetInteriorRingN(i - 1).NumPoints;
                    writer.Write((int) count);
                }
            }

            // Write Coordinates
            for (int i = 0; i < polygon.NumPoints; i++)
                Write(polygon.Coordinates[i], writer);
        }
 /**
  * Finds a best-fit plane for the polygon, 
  * by sampling a few points from the exterior ring.
  * <p>
  * The algorithm used is Newell's algorithm:
  * - a base point for the plane is determined from the average of all vertices
  * - the normal vector is determined by
  *   computing the area of the projections on each of the axis planes
  * 
  * @param poly the polygon to determine the plane for
  * @return the best-fit plane
  */
 private static Plane3D FindBestFitPlane(IPolygon poly)
 {
     var seq = poly.ExteriorRing.CoordinateSequence;
     var basePt = AveragePoint(seq);
     var normal = AverageNormal(seq);
     return new Plane3D(normal, basePt);
 }
        public void HandleNewInput(IPolygon geometry)
        {
            // Reset labels
            lbNumVert2.Text = "-";
            lbNumTri2.Text = "-";
            lbNumSeg2.Text = "-";

            lbNumVert.Text = geometry.Points.Count.ToString();
            lbNumSeg.Text = geometry.Segments.Count().ToString();
            lbNumTri.Text = "0";

            // Statistics labels
            lbAreaMin.Text = "-";
            lbAreaMax.Text = "-";
            lbEdgeMin.Text = "-";
            lbEdgeMax.Text = "-";
            lbAngleMin.Text = "-";
            lbAngleMax.Text = "-";

            // Quality labels
            lbQualAlphaMin.Text = "-";
            lbQualAlphaAve.Text = "-";
            lbQualAspectMin.Text = "-";
            lbQualAspectAve.Text = "-";

            angleHistogram1.SetData(null, null);
        }
 public void HandleMeshImport(IPolygon geometry, Mesh mesh)
 {
     // Previous mesh stats
     lbNumVert2.Text = "-";
     lbNumTri2.Text = "-";
     lbNumSeg2.Text = "-";
 }
 protected override void OnRenderInternal(Map map, IPolygon polygon, IGraphics g)
 {
     IPoint pt = polygon.Centroid;
     Point renderingOrigin = Point.Truncate(Transform.WorldtoMap(pt.Coordinate, map));
     g.RenderingOrigin = new PointStruct(renderingOrigin.X, renderingOrigin.Y);
     base.OnRenderInternal(map, polygon, g);
 }
Example #6
0
        // 0 0 0 0
        // 0 1 0 0
        // 0 1 2 0
        // 0 1 2 3 0 ...
        private void AppendCurvePoint(IPolygon polygon, ICoordinate worldPos)
        {
            List<ICoordinate> vertices = new List<ICoordinate>();

            ILineString linearRing = polygon.ExteriorRing;
            for (int i = 0; i < linearRing.Coordinates.Length; i++)
            {
                if (linearRing.Coordinates.Length <= 4)
                {
                    if (1 == i)
                    {
                        if (linearRing.Coordinates[0].Equals2D(linearRing.Coordinates[1]))
                        {
                            // 0 0 ? 0 -> 0 1 ? 0 
                            vertices.Add(worldPos);
                        }
                        else
                        {
                            // 0 1 ? 0 -> 0 1 ? 0
                            vertices.Add(linearRing.Coordinates[i]);
                        }
                    }
                    else if (2 == i)
                    {
                        if (linearRing.Coordinates[1].Equals2D(linearRing.Coordinates[2]))
                        {
                            // 0 0 0 0 -> 0 1 1 0
                            vertices.Add(worldPos);
                        }
                        else
                        {
                            // 0 1 2 0 -> 0 1 2 3 0
                            vertices.Add(linearRing.Coordinates[i]);
                            vertices.Add(worldPos);
                        }
                    }
                    else
                    {
                        vertices.Add(linearRing.Coordinates[i]);
                    }
                }
                else
                {
                    if (i == (linearRing.Coordinates.Length - 1))
                    {
                        // insert before last point to keep ring closed
                        vertices.Add(worldPos);
                    }
                    vertices.Add(linearRing.Coordinates[i]);
                }
            }
            int index = FeatureProvider.GetFeatureCount() - 1;
            ILinearRing newLinearRing = GeometryFactory.CreateLinearRing(vertices.ToArray());
            IPolygon newPolygon = GeometryFactory.CreatePolygon(newLinearRing, null);
            //##layerEditor.UpdateCurvePointInserted(index, newPolygon, vertices.Count - 1);
            //((FeatureProvider)layerEditor.VectorLayer.DataSource).UpdateGeometry(index, newPolygon);
            ((Feature)FeatureProvider.Features[index]).Geometry = newPolygon;
            Layer.RenderRequired = true;
            // do not remove see newline MapControl.SelectTool.Select((VectorLayer)Layer, newPolygon, -1);
        }
Example #7
0
		/// <summary>
		/// Create a new Station object providing a mainPicture which contains the required EXIF metadata
		/// </summary>
		/// <param name="image"></param>
		public Station(string stationID, IPolygon grid, string image)
		{			
			_stationID=stationID;
			_grid=grid;
			
			this.MetadataFromImage(image);
			
		}
Example #8
0
		/// <summary>
		/// Create a new Station object typing all the property values
		/// </summary>
		/// <param name="lat"></param>
		/// <param name="lon"></param>
		/// <param name="alt"></param>
		/// <param name="compass"></param>
		public Station (string stationID, IPolygon grid, double lat, double lon, double alt, double compass)
		{
			_lat=lat;
			_lon=lon;
			_alt=alt;
			_compass=compass;
			_stationID=stationID;
		}
 public static void ComputeDistance(IPolygon poly, Coordinate pt, PointPairDistance ptDist)
 {
     ComputeDistance(poly.ExteriorRing, pt, ptDist);
     for (var i = 0; i < poly.NumInteriorRings; i++)
     {
         ComputeDistance(poly.GetInteriorRingN(i), pt, ptDist);
     }
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="p"></param>
 /// <returns></returns>
 private bool HasRepeatedPoint(IPolygon p)
 {
     if (HasRepeatedPoint(p.ExteriorRing.Coordinates))
         return true;
     for (int i = 0; i < p.NumInteriorRings; i++)
         if (HasRepeatedPoint(p.GetInteriorRingN(i).Coordinates)) 
             return true;            
     return false;
 }
 private void Benchmark(IPolygon poly)
 {
     var start = DateTime.Now;
     var valid = poly.IsValid;
     var end = DateTime.Now;
     var diff = end - start;
     var td = diff.TotalSeconds;
     LogLine("{0} \t{1} \t{2} \t{3}", poly.NumInteriorRings, poly.NumPoints, valid, td);
 }
        private static bool IsAllCW(IPolygon poly)
        {
            IList<Coordinate> shell = poly.Shell.Coordinates;
            for (int i = 0, c = shell.Count - 3; i < c; i++)
            {
                if (CgAlgorithms.ComputeOrientation(shell[i], shell[i + 1], shell[i + 2]) == 1)
                    return false;
            }

            return true;
        }
        public Triangulatable(IPolygon polygon)
        {
            List<Vector2D> vPoints = new List<Vector2D>(polygon.VerticesArray);
             List<TriangulationPoint> tPoints = vPoints.ConvertAll(p => (TriangulationPoint) (p));

             if (tPoints.Count < 3) throw new ArgumentException("List has fewer than 3 points", "points");

             // Lets do one sanity check that first and last point haven't got same position
             // It's something that often happens when importing polygon data from other formats
             if (tPoints[0].Equals(tPoints[tPoints.Count - 1])) tPoints.RemoveAt(tPoints.Count - 1);

             points.AddRange(tPoints);
        }
        /// <summary>
        /// Save a polygon geometry to disk.
        /// </summary>
        /// <param name="mesh">An instance of the <see cref="IPolygon" /> class.</param>
        /// <param name="filename">The path of the file to save.</param>
        public static void Write(IPolygon polygon, string filename)
        {
            foreach (IPolygonFormat format in formats)
            {
                if (format != null && format.IsSupported(filename))
                {
                    format.Write(polygon, filename);
                    return;
                }
            }

            throw new Exception("File format not supported.");
        }
 public static Boolean ContainsPointInPolygon(Coordinate p, IPolygon poly)
 {
     if (poly.IsEmpty) return false;
     ILinearRing shell = (ILinearRing)poly.ExteriorRing;
     if (!IsPointInRing(p, shell)) return false;
     // now test if the point lies in or on the holes
     for (int i = 0; i < poly.NumInteriorRings; i++)
     {
         ILinearRing hole = (ILinearRing)poly.GetInteriorRingN(i);
         if (IsPointInRing(p, hole)) return false;
     }
     return true;
 }
Example #16
0
 /// <summary>
 /// 
 /// </summary>
 public PolygonSamples() : base(new GeometryFactory(new PrecisionModel(PrecisionModels.Fixed)))
 {
     shell = Factory.CreateLinearRing(new ICoordinate[] { new Coordinate(100,100),
                                                          new Coordinate(200,100),
                                                          new Coordinate(200,200),                
                                                          new Coordinate(100,200),
                                                          new Coordinate(100,100), });
     hole = Factory.CreateLinearRing(new ICoordinate[] {  new Coordinate(120,120),
                                                          new Coordinate(180,120),
                                                          new Coordinate(180,180),                                                                                
                                                          new Coordinate(120,180),                                                                
                                                          new Coordinate(120,120), });
     polygon = Factory.CreatePolygon(shell, new ILinearRing[] { hole, });
 }
        /// <summary>
        /// Insert segments into the mesh.
        /// </summary>
        /// <param name="input">The polygon.</param>
        /// <param name="options">Constraint options.</param>
        public void Apply(IPolygon input, ConstraintOptions options)
        {
            behavior.Poly = input.Segments.Count > 0;

            // Copy constraint options
            if (options != null)
            {
                behavior.ConformingDelaunay = options.ConformingDelaunay;
                behavior.Convex = options.Convex;
                behavior.NoBisect = options.SegmentSplitting;

                if (behavior.ConformingDelaunay)
                {
                    behavior.Quality = true;
                }
            }

            //if (input.EdgeMarkers != null)
            //{
            //    behavior.UseBoundaryMarkers = true;
            //}

            behavior.useRegions = input.Regions.Count > 0;

            // Ensure that no vertex can be mistaken for a triangular bounding
            // box vertex in insertvertex().
            mesh.infvertex1 = null;
            mesh.infvertex2 = null;
            mesh.infvertex3 = null;

            if (behavior.useSegments)
            {
                // Segments will be introduced next.
                mesh.checksegments = true;

                // Insert PSLG segments and/or convex hull segments.
                FormSkeleton(input);
            }

            if (behavior.Poly && (mesh.triangles.Count > 0))
            {
                // Copy holes and regions
                mesh.holes.AddRange(input.Holes);
                mesh.regions.AddRange(input.Regions);

                // Carve out holes and concavities.
                CarveHoles();
            }
        }
Example #18
0
 public void Init()
 {
     shell = Factory.CreateLinearRing(new ICoordinate[] {    new Coordinate(100,100),
                                                             new Coordinate(200,100),
                                                             new Coordinate(200,200),                
                                                             new Coordinate(100,200),
                                                             new Coordinate(100,100), });
     // NOTE: Hole is created with not correct order for holes
     hole = Factory.CreateLinearRing(new ICoordinate[] {      new Coordinate(120,120),
                                                             new Coordinate(180,120),
                                                             new Coordinate(180,180),                                                                                
                                                             new Coordinate(120,180),                                                                
                                                             new Coordinate(120,120), });
     polygon = Factory.CreatePolygon(shell, new ILinearRing[] { hole, });
 }
        public static void AssertPolygonsEqual(IPolygon poly1, IPolygon poly2)
        {
            Assert.IsNotNull(poly1);
            Assert.IsNotNull(poly2);

            ILineString line1 = poly1.Shell;
            ILineString line2 = poly2.Shell;

            Assert.AreEqual(line1.Coordinates.Length, line2.Coordinates.Length, "Number of coordinates between polygons doesn't match");

            for (int i = 0; i < line2.Coordinates.Length; i++)
            {
                AssertCoordinatesEqual(line2.Coordinates[i], line1.Coordinates[i]);
            }
        }
        public void Render(LittleSharpRenderEngine engine, Graphics graphics, IPolygon polygon, IAreaStyle style)
        {
            if (polygon == null || style == null) return;

            System.Drawing.Drawing2D.GraphicsPath gp = new System.Drawing.Drawing2D.GraphicsPath();

            gp.AddPolygon(RenderUtil.CoordToPoint(polygon.Shell.Coordinates));
            foreach (ILinearRing l in polygon.Holes)
                gp.AddPolygon(RenderUtil.CoordToPoint(l.Coordinates));
            gp.CloseFigure();

            if (style.Fill != null) RenderUtil.RenderFill(engine, graphics, gp, style.Fill);

            if (style.Outline != null) RenderUtil.RenderOutline(engine, graphics, gp, style.Outline);
        }
        private void AddPolygon(IPolygon polygon, GraphicsPath graphicsPath)
        {
            if (polygon == null)
                throw new ArgumentNullException("polygon");

            ILineString exterior = polygon.ExteriorRing;
            IEnumerable<PointF> coords = this.GetCoords(exterior);
            graphicsPath.AddPolygon(coords.ToArray());

            foreach (ILineString ring in polygon.InteriorRings)
            {
                coords = this.GetCoords(ring);
                graphicsPath.AddPolygon(coords.ToArray());
            }
        }
Example #22
0
        public static string ConvertPolygonToJson(IPolygon poly)
        {
            // Note: According to the specification for GeoJSON, the CRS tags are deprecated and no
            // longer used. See: https://tools.ietf.org/html/draft-butler-geojson-06#page-9
            // GeoJSON is supposed to be defaulted and assumed to always be projected
            // as CRS 84 / EPSG:4326

            // with the above in mind, should we reproject the polygon?

            // Project polygon to GeoJSON default EPSG:4326
            //ISpatialReferenceFactory2 sre = (ISpatialReferenceFactory2)new SpatialReferenceEnvironment();
            //ISpatialReference sr = sre.CreateSpatialReference(4326);
            //poly.Project(sr);
            //poly.SpatialReference = sr;

            JsonPolygon jsonPoly = new JsonPolygon();

            IPointCollection pc = (IPointCollection)poly;
            IEnvelope bbox = poly.Envelope;

            List<List<double>> allPoints = new List<List<double>>();

            for (int i = 0; i < pc.PointCount; i++)
            {
                double x = pc.get_Point(i).X;
                double y = pc.get_Point(i).Y;

                List<double> point = new List<double>();
                point.Add(x);
                point.Add(y);

                allPoints.Add(point);
            }

            // the GeoJSON spec has the coordinate array a three-array stagger (points in arrays, holes in array around that, multipoly in another array)
            // we don't deal with multipoly or holes in SUITT, but we need to make sure the format matches, hence the wierd List
            jsonPoly.coordinates.Add(allPoints);

            //define bbox: minx, miny, maxx, maxy
            jsonPoly.bbox.Add(bbox.XMin);
            jsonPoly.bbox.Add(bbox.YMin);
            jsonPoly.bbox.Add(bbox.XMax);
            jsonPoly.bbox.Add(bbox.YMax);

            // set the projection
            //jsonPoly.crs = new GeoJsonCRS("EPSG:" + poly.SpatialReference.FactoryCode.ToString());
            return JsonConvert.SerializeObject(jsonPoly);
        }
Example #23
0
        public static IMapPoint Center(IPolygon polygon)
        {
            IEnumerable<IMapPoint> pc = polygon.GetPoints();
            double x = 0;
            double y = 0;

            foreach (IMapPoint p in pc)
            {
                x += p.X;
                y += p.Y;
            }
            x /= pc.Count();
            y /= pc.Count();
            IMapPoint center = Runtime.geometryEngine.newMapPoint(x, y);
            return center;
        }
        /// <summary>
        /// Method that does the actual rendering of geometries
        /// </summary>
        /// <param name="map">The map</param>
        /// <param name="polygon">The feature</param>
        /// <param name="g">The graphics object</param>
        protected override void OnRenderInternal(Map map, IPolygon polygon, IGraphics g)
        {
            // convert points
            var pts = /*LimitValues(*/polygon.TransformToImage(map)/*)*/;

            // clip
            if (UseClipping)
                pts = RendererHelper.ClipPolygon(pts, map.Size.Width, map.Size.Height);
            
            // fill the polygon
            if (Fill != null)
                g.FillPolygon(Fill, pts);
            
            // outline the polygon
            if (Outline != null)
                g.DrawPolygon(Outline, pts);
        }
        /// <inheritdoc />
        public IMesh Triangulate(IPolygon polygon, ConstraintOptions options, QualityOptions quality)
        {
            var mesh = (Mesh)triangulator.Triangulate(polygon.Points, config);

            var cmesher = new ConstraintMesher(mesh, config);
            var qmesher = new QualityMesher(mesh, config);

            mesh.SetQualityMesher(qmesher);

            // Insert segments.
            cmesher.Apply(polygon, options);

            // Refine mesh.
            qmesher.Apply(quality);

            return mesh;
        }
Example #26
0
        /// <summary>
        /// �½���ͼ��
        /// </summary>
        public IFeatureClass CreatePolygonLayer(IPolygon polygon)
        {
            //LocalFilePath = sfdPoint.FileName;
               FilePath = Application.StartupPath + "\\tempSHP";
               FileName = "test";

               IFields pFields = new FieldsClass();
               IFieldsEdit pFieldsEdit = pFields as IFieldsEdit;
               IField pField = new FieldClass();
               IFieldEdit pFieldEdit = pField as IFieldEdit;
               pFieldEdit.Name_2 = "SHAPE";
               pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;

               IGeometryDef pGeometryDef = new GeometryDefClass();
               IGeometryDefEdit pGeometryDefEdit = pGeometryDef as IGeometryDefEdit;
               pGeometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
               pFieldEdit.GeometryDef_2 = pGeometryDef;
               pFieldsEdit.AddField(pField);

               pField = new FieldClass();
               pFieldEdit = pField as IFieldEdit;
               pFieldEdit.Name_2 = "HEIGHT";
               pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
               pFieldsEdit.AddField(pField);

               IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactoryClass();
               IFeatureWorkspace pFeatureWorkspace = pWorkspaceFactory.OpenFromFile(FilePath, 0) as IFeatureWorkspace;
               IFeatureClass feaC = pFeatureWorkspace.CreateFeatureClass(FileName, pFields, null, null, esriFeatureType.esriFTSimple, "SHAPE", "");
               IFeature pFeature = feaC.CreateFeature();
               pFeature.Shape = polygon as IGeometry;
               pFeature.Store();

               IFeatureCursor feaCur = feaC.Search(null, true);
               pFeature = feaCur.NextFeature();
               while (pFeature != null)
               {
               //pFeature.set_Value(2, "181");
               pFeature.Store();
               pFeature = feaCur.NextFeature();
               }

               //m_mapControl.AddShapeFile(FilePath, FileName);
               //m_mapControl.ActiveView.Refresh();
               return feaC;
        }
Example #27
0
        /// <summary>
        /// 
        /// </summary>
        public GMLTesting() 
        {
            point = Factory.CreatePoint(new Coordinate(100, 100));

            ICoordinate[] coordinates = new ICoordinate[]
            {
                 new Coordinate(10,10),
                 new Coordinate(20,20),
                 new Coordinate(20,10),                 
            };
            line = Factory.CreateLineString(coordinates);

            coordinates = new ICoordinate[]
            {
                new Coordinate(100,100),
                new Coordinate(200,100),
                new Coordinate(200,200),                
                new Coordinate(100,200),
                new Coordinate(100,100),
            };
            ICoordinate[] interior1 = new ICoordinate[] 
            { 
                new Coordinate(120,120),
                new Coordinate(180,120),
                new Coordinate(180,180),                
                new Coordinate(120,180),
                new Coordinate(120,120),
            };
            ILinearRing linearRing = Factory.CreateLinearRing(coordinates);
            ILinearRing[] holes = new ILinearRing[] { Factory.CreateLinearRing(interior1), };
            polygon = Factory.CreatePolygon(linearRing, holes);

            coordinates = new ICoordinate[]
            {
                new Coordinate(100,100),
                new Coordinate(200,200),
                new Coordinate(300,300),                
                new Coordinate(400,400),
                new Coordinate(500,500),
            };
            multiPoint = Factory.CreateMultiPoint(coordinates);

            writer = new GMLWriter();
            reader = new GMLReader();
        }
Example #28
0
 /// <summary>
 /// 通过簇的点集计算簇的凸包
 /// </summary>
 /// <returns></returns>
 public void CreateConvexHull(ISpatialReference spatialReference)
 {
     //少于3个点就不做
     if (m_pointsList.Count < 3)
         return;
     IGeometryCollection geometryCollection = new MultipointClass();
     for (int i = 0; i < m_pointsList.Count; i++)
     {
         geometryCollection.AddGeometry(m_pointsList[i] as IGeometry);
     }
     ITopologicalOperator pTopological = geometryCollection as ITopologicalOperator;
     IGeometry g = pTopological.ConvexHull();
     if (g.GeometryType != esriGeometryType.esriGeometryPolygon)
         return;
     IPolygon convexHull = g as IPolygon;
     convexHull.SpatialReference = spatialReference;
     m_convexHull = convexHull;
 }
 public static IGeometry GetPolygonShell(IGeometry g)
 {
     if (g is IPolygon)
     {
         ILinearRing shell = (ILinearRing)((IPolygon)g).ExteriorRing;
         return g.Factory.CreatePolygon(shell, null);
     }
     if (g is IMultiPolygon)
     {
         IPolygon[] poly = new IPolygon[g.NumGeometries];
         for (int i = 0; i < g.NumGeometries; i++)
         {
             ILinearRing shell = (ILinearRing)((IPolygon)g.GetGeometryN(i)).ExteriorRing;
             poly[i] = g.Factory.CreatePolygon(shell, null);
         }
         return g.Factory.CreateMultiPolygon(poly);
     }
     return null;
 }
Example #30
0
 private void AddPolygon(SdoGeometry sdoGeometry, IPolygon polygon)
 {
     int numInteriorRings = polygon.NumInteriorRings;
     decimal[] info = new decimal[(numInteriorRings + 1) * 3];
     int ordinatesOffset = 1;
     if (sdoGeometry.OrdinatesArray != null)
     {
         ordinatesOffset = sdoGeometry.OrdinatesArray.Length + 1;
     }
     double?[] ordinates = new double?[] { };
     for (int i = 0; i < info.Length; i++)
     {
         ElementType et;
         ICoordinate[] coords;
         if (i == 0)
         {
             et = ElementType.EXTERIOR_RING_STRAIGHT_SEGMENTS;
             coords = polygon.ExteriorRing.Coordinates;
             if (!CGAlgorithms.IsCCW(coords))
             {
                 coords = ReverseRing(coords);
             }
         }
         else
         {
             et = ElementType.INTERIOR_RING_STRAIGHT_SEGMENTS;
             coords = polygon.InteriorRings[i - 1].Coordinates;
             if (CGAlgorithms.IsCCW(coords))
             {
                 coords = ReverseRing(coords);
             }
         }
         //info.setElement(i, ordinatesOffset, et, 0);
         info[i + 0] = ordinatesOffset;
         info[i + 1] = (decimal)et;
         info[i + 2] = 0;
         ordinates = ConvertAddCoordinates(ordinates, coords, sdoGeometry.Dimensionality, sdoGeometry.LRS > 0);
         ordinatesOffset = ordinates.Length + 1;
     }
     sdoGeometry.addElement(info);
     sdoGeometry.AddOrdinates(ordinates);
 }
Example #31
0
        private void ReadPolygonShape(Shape shape)
        {
            List <ILinearRing> shells = new List <ILinearRing>();
            List <ILinearRing> holes  = new List <ILinearRing>();

            foreach (PartRange part in shape.Range.Parts)
            {
                List <Coordinate> coords = new List <Coordinate>();
                int i = part.StartIndex;
                foreach (Vertex d in part)
                {
                    Coordinate c = new Coordinate(d.X, d.Y);
                    if (shape.M != null && shape.M.Length > 0)
                    {
                        c.M = shape.M[i];
                    }
                    if (shape.Z != null && shape.Z.Length > 0)
                    {
                        c.Z = shape.Z[i];
                    }
                    i++;
                    coords.Add(c);
                }
                LinearRing ring = new LinearRing(coords.ToArray());
                if (shape.Range.Parts.Count == 1)
                {
                    shells.Add(ring);
                }
                else
                {
                    if (CGAlgorithms.IsCCW(ring.Coordinates))
                    {
                        holes.Add(ring);
                    }
                    else
                    {
                        shells.Add(ring);
                    }
                }
            }
            if (shells.Count == 0 && holes.Count > 0)
            {
                shells = holes;
                holes  = new List <ILinearRing>();
            }
            //// Now we have a list of all shells and all holes
            List <ILinearRing>[] holesForShells = new List <ILinearRing> [shells.Count];
            for (int i = 0; i < shells.Count; i++)
            {
                holesForShells[i] = new List <ILinearRing>();
            }

            // Find holes
            for (int i = 0; i < holes.Count; i++)
            {
                ILinearRing testRing = holes[i];
                ILinearRing minShell = null;
                Envelope    minEnv   = null;
                Envelope    testEnv  = testRing.EnvelopeInternal;
                Coordinate  testPt   = testRing.Coordinates[0];
                for (int j = 0; j < shells.Count; j++)
                {
                    ILinearRing tryRing = shells[j];
                    Envelope    tryEnv  = tryRing.EnvelopeInternal;
                    if (minShell != null)
                    {
                        minEnv = minShell.EnvelopeInternal;
                    }

                    // Check if this new containing ring is smaller than the current minimum ring
                    if (tryEnv.Contains(testEnv) && (CGAlgorithms.IsPointInRing(testPt, tryRing.Coordinates) || (PointInList(testPt, tryRing.Coordinates))))
                    {
                        if (minShell == null || minEnv.Contains(tryEnv))
                        {
                            minShell = tryRing;
                        }
                        holesForShells[j].Add(holes[i]);
                    }
                }
            }

            var polygons = new IPolygon[shells.Count];

            for (int i = 0; i < shells.Count; i++)
            {
                polygons[i] = new Polygon(shells[i], holesForShells[i].ToArray());
            }

            if (polygons.Length == 1)
            {
                _basicGeometry = polygons[0];
            }
            else
            {
                // It's a multi part
                _basicGeometry = new MultiPolygon(polygons);
            }
            _featureType = FeatureType.Polygon;
        }
Example #32
0
 public Park(string name, string category, IPolygon polygon, string resolution, string territory, bool openingState) : base(name, category, polygon, resolution, territory)
 {
     cost = new Cost();
     this.openingState = openingState;
 }
Example #33
0
        public MapperHierarchyNode(ModelMapper mapper, ICanvas canvas, IGraphElement parent, HierarchyViewer viewer)
            : base()
        {
            Mapper  = mapper;
            FCanvas = canvas;
            FViewer = viewer;

            MouseClick       += FViewer.MouseClickHandler;
            MouseDoubleClick += FViewer.MouseDoubleClickHandler;
            Tag = mapper.Model;

            //graphelements
            FBackground = canvas.CreateRectangle(this);
            FPoly       = canvas.CreatePoly(this);
            FText       = canvas.CreateText(null, "");
            FIcon       = FCanvas.CreateRectangle(null);

            parent.Add(FBackground);
            FBackground.Add(FPoly);
            FBackground.Add(FText);
            FBackground.Add(FIcon);

            //compute level of depth
            IGraphElement p = FBackground;

            while (p.Parent != null)
            {
                FDepth++;
                p = p.Parent;
            }
            FDepth -= 1;

            //init static properties via Mapper
            if (Mapper.CanMap <ISelectable>())
            {
                FSelectable = Mapper.Map <ISelectable>();
                FSelectable.SelectionChanged += selectable_SelectionChanged;
                Selected = FSelectable.Selected;
            }

            if (Mapper.CanMap <IDecoratable>())
            {
                FDecoratable = Mapper.Map <IDecoratable>();
                FDecoratable.DecorationChanged += decorated_DecorationChanged;
            }

            if (Mapper.CanMap <ILinkSource>())
            {
                FLinkSource = Mapper.Map <ILinkSource>();

                FLinkSourceRectangle = FCanvas.CreateRectangle(null);
                FBackground.Add(FLinkSourceRectangle);
                FLinkOffset = FTextOffset;
            }

            if (Mapper.CanMap <ILinkSink>())
            {
                FLinkSink = Mapper.Map <ILinkSink>();

                FLinkSinkRectangle = FCanvas.CreateRectangle(null);
                FBackground.Add(FLinkSinkRectangle);
            }

            if (Mapper.CanMap <INamed>())
            {
                FNamed          = Mapper.Map <INamed>();
                FNamed.Renamed += named_Renamed;
                SetCaption(FNamed.Name);
            }

            if (Mapper.CanMap <IParent>())
            {
                var node = Mapper.Map <IParent>();
                if (node.Childs != null)
                {
                    // Keep Nodes and items in sync
                    FSynchronizer         = FSubTree.SyncWith(node.Childs, CreateChildNode);
                    FSynchronizer.Synced += synchronizer_Synced;
                }
            }

            //init dynamic properties via Mapper
            UpdateColors();
            UpdateIcon();
            UpdateLinkSink();
            UpdateLinkSource();
        }
Example #34
0
        //双击则创建该线,并弹出缓冲窗体
        public override void OnDblClick()
        {
            //获取折线 并获取当前视图的屏幕显示
            if (m_pNewPolygonFeedback == null)
            {
                return;
            }
            IPolygon pPolygon = m_pNewPolygonFeedback.Stop();

            m_pNewPolygonFeedback = null;

            //不存在,为空。尺寸不够均退出
            if (pPolygon == null || pPolygon.IsEmpty)
            {
                return;
            }
            //xisheng 判断面积的高度,宽度时需判断是什么单位,若是经纬度则需要转换。20111220
            double        w      = pPolygon.Envelope.Width;
            double        h      = pPolygon.Envelope.Height;
            UnitConverter conver = new UnitConverterClass();

            if (m_MapControl.Map.MapUnits == esriUnits.esriDecimalDegrees)
            {
                w = conver.ConvertUnits(w, esriUnits.esriDecimalDegrees, esriUnits.esriMeters);
                h = conver.ConvertUnits(h, esriUnits.esriDecimalDegrees, esriUnits.esriMeters);
            }
            if (w < 0.01 || h < 0.01)
            {
                return;
            }
            //xisheng 20111220 end *********************************************************

            //创建Topo对象,简化后统一空间参考
            ITopologicalOperator pTopo = (ITopologicalOperator)pPolygon;

            pTopo.Simplify();
            pPolygon.Project(m_MapControl.Map.SpatialReference);

            if (m_frmQuery == null)
            {
                m_frmQuery             = new frmQuery(m_MapControl, m_enumQueryMode);
                m_frmQuery.Owner       = m_mainFrm;
                m_frmQuery.FormClosed += new FormClosedEventHandler(frmQuery_FormClosed);
            }
            if (this.WriteLog)
            {
                Plugin.LogTable.Writelog("面缓冲查询");//xisheng 日志记录 0928;
            }
            //清除上次的所有元素
            (m_MapControl.Map as IGraphicsContainer).DeleteAllElements();
            m_frmBufferSet = new frmBufferSet(pPolygon as IGeometry, m_MapControl.Map, m_frmQuery);
            IGeometry pGeometry = m_frmBufferSet.GetBufferGeometry();

            if (pGeometry == null || m_frmBufferSet.Res == false)
            {
                return;
            }
            // m_frmQuery.Show();
            ///ZQ 20111119  modify
            //m_frmQuery.FillData(m_MapControl.ActiveView.FocusMap, pGeometry,m_frmBufferSet.pesriSpatialRelEnum);
            _QueryBar.m_pMapControl = m_MapControl;
            _QueryBar.EmergeQueryData(m_MapControl.ActiveView.FocusMap, pGeometry, m_frmBufferSet.pesriSpatialRelEnum);
            try
            {
                DevComponents.DotNetBar.Bar pBar = _QueryBar.Parent.Parent as DevComponents.DotNetBar.Bar;
                if (pBar != null)
                {
                    pBar.AutoHide = false;
                    //pBar.SelectedDockTab = 1;
                    int tmpindex = pBar.Items.IndexOf("dockItemDataCheck");
                    pBar.SelectedDockTab = tmpindex;
                }
            }
            catch
            { }
        }
Example #35
0
 //窗体关闭时 刷新前景
 private void frm_FormClosed(object sender, FormClosedEventArgs e)
 {
     m_Polygon = null;
     m_pActiveView.PartialRefresh(esriViewDrawPhase.esriViewForeground, null, null);
 }
Example #36
0
    private void DrawMeasure(Graphics graphics, IGeometry geometry)
    {
        string measureUnits = _appSettings.MeasureUnits;
        bool   inFeet       = measureUnits == "feet" || measureUnits == "both";
        bool   inMeters     = measureUnits == "meters" || measureUnits == "both";

        System.Drawing.Font font = _appSettings.MeasureFont;
        font = new System.Drawing.Font(font.FontFamily, Convert.ToSingle(font.Size * _resolution), font.Style, font.Unit);
        SolidBrush brush     = new SolidBrush(Color.FromArgb(64, 64, 64));
        SolidBrush glowBrush = new SolidBrush(Color.White);

        StringFormat format = new StringFormat();

        format.Alignment     = StringAlignment.Center;
        format.LineAlignment = StringAlignment.Center;

        double           convert = 1 / (_appSettings.MapUnits == "feet" ? 1 : Constants.MetersPerFoot);
        StringCollection text    = new StringCollection();

        switch (geometry.OgcGeometryType)
        {
        case OgcGeometryType.LineString:
            ILineString lineString = (ILineString)geometry;
            double      d;

            if (_appSettings.MapCoordinateSystem.Equals(_appSettings.MeasureCoordinateSystem))
            {
                d = lineString.Length * convert;
            }
            else
            {
                ILineString measureLineString = _appSettings.MapCoordinateSystem.ToGeodetic(lineString);
                measureLineString = _appSettings.MeasureCoordinateSystem.ToProjected(measureLineString);
                convert           = 1 / (_appSettings.MeasureCoordinateSystem.MapUnits == "feet" ? 1 : Constants.MetersPerFoot);
                d = measureLineString.Length * convert;
            }

            if (inFeet)
            {
                text.Add(d < 5280 ? d.ToString("0") + " ft" : (d / 5280).ToString("0.0") + " mi");
            }

            if (inMeters)
            {
                d *= Constants.MetersPerFoot;
                text.Add(d < 1000 ? d.ToString("0") + " m" : (d / 1000).ToString("0.0") + " km");
            }

            IPoint p;
            double angle;

            GetMidpoint(lineString, out p, out angle);

            angle = -(angle * 180 / Math.PI);
            angle = angle < -90 || 90 < angle ? angle + 180 : angle < 0 ? angle + 360 : angle;

            p = _transform.ReverseTransform(p);

            float x = Convert.ToSingle(p.Coordinate.X * _resolution);
            float y = Convert.ToSingle(p.Coordinate.Y * _resolution);

            format.LineAlignment = StringAlignment.Far;

            int[] pos = new int[] { 0, 1, 2, 3, 5, 6, 7, 8, 4 };

            for (int i = 0; i < 9; ++i)
            {
                float offsetX = (pos[i] % 3) - 1;
                float offsetY = Convert.ToSingle(Math.Floor(pos[i] / 3.0)) - 1;

                System.Drawing.Drawing2D.GraphicsState state = graphics.Save();
                graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
                graphics.TranslateTransform(x, y);
                graphics.RotateTransform(Convert.ToSingle(angle));
                graphics.DrawString(text.Join("\n"), font, i < 8 ? glowBrush : brush, Convert.ToSingle(offsetX * _resolution), Convert.ToSingle(offsetY - 3 * _resolution), format);
                graphics.Restore(state);
            }
            break;

        case OgcGeometryType.Polygon:
            IPolygon polygon = (IPolygon)geometry;
            IPoint   c       = polygon.Centroid;

            if (c != null)
            {
                double a;

                if (_appSettings.MapCoordinateSystem.Equals(_appSettings.MeasureCoordinateSystem))
                {
                    a = polygon.Area * convert * convert;
                }
                else
                {
                    IPolygon measurePolygon = _appSettings.MapCoordinateSystem.ToGeodetic(polygon);
                    measurePolygon = _appSettings.MeasureCoordinateSystem.ToProjected(measurePolygon);
                    convert        = 1 / (_appSettings.MeasureCoordinateSystem.MapUnits == "feet" ? 1 : Constants.MetersPerFoot);
                    a = measurePolygon.Area * convert * convert;
                }

                double acres = a / Constants.SquareFeetPerAcre;

                if (inFeet)
                {
                    double squareMile = Constants.FeetPerMile * Constants.FeetPerMile;
                    text.Add(a <= squareMile ? a.ToString("0") + " sq ft" : (a / squareMile).ToString("0.00") + " sq mi");
                }

                if (inMeters)
                {
                    a *= Constants.MetersPerFoot * Constants.MetersPerFoot;
                    text.Add(a <= 100000 ? a.ToString("0") + " sq m" : (a / 1000000).ToString("0.00") + " sq km");
                }

                if (inFeet)
                {
                    text.Add(acres.ToString("0.00") + " acres");
                }

                DrawText(graphics, c, text.Join("\n"), font, brush, glowBrush, 0, 0, format);
            }
            break;
        }
    }
Example #37
0
        /// <summary>
        ///鼠标点击操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void axMapcontrol_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            Dwnpoint = new PointClass();
            Dwnpoint = this.axMapcontrol.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);
            if (e.button != 1)
            {
                return;
            }
            #region 地图操作
            switch (pMouseOperate)
            {
            case  "区域导出":
                //删除绘制的图片
                this.axMapcontrol.ActiveView.GraphicsContainer.DeleteAllElements();
                this.axMapcontrol.ActiveView.Refresh();
                IPolygon polygon = DrawPolygon(this.axMapcontrol);
                if (polygon == null)
                {
                    return;
                }
                ExportMap.AddElement(polygon, this.axMapcontrol.ActiveView);
                if (polygon == null)
                {
                    return;
                }
                if (exportmapFrm == null || exportmapFrm.IsDisposed)
                {
                    exportmapFrm             = new ExportMapFrm(this.axMapcontrol);
                    exportmapFrm.IsRgion     = true;
                    exportmapFrm.GetGeometry = polygon as IGeometry;
                    exportmapFrm.Show();
                }
                exportmapFrm.GetGeometry = polygon;
                exportmapFrm.IsRgion     = true;
                //获取当前控件焦点
                exportmapFrm.Activate();
                break;

            case "MeasureLength":
                if (m_newline == null)
                {
                    m_newline         = new NewLineFeedbackClass();
                    m_newline.Display = this.axMapcontrol.ActiveView.ScreenDisplay;
                    m_newline.Start(Dwnpoint);
                    TotalLength = 0;
                }
                else
                {
                    TotalLength += SegmentLength;
                    m_newline.AddPoint(Dwnpoint);
                }
                break;

            case "MeasureArea":
                if (m_newpolygon == null || Area_Pocoll == null)
                {
                    m_newpolygon         = new NewPolygonFeedbackClass();
                    Area_Pocoll          = new PolygonClass();
                    m_newpolygon.Display = this.axMapcontrol.ActiveView.ScreenDisplay;
                    m_newpolygon.Start(Dwnpoint);
                    Area_Pocoll.AddPoint(Dwnpoint);
                    TotalLength = 0;
                }
                else
                {
                    m_newpolygon.AddPoint(Dwnpoint);
                    Area_Pocoll.AddPoint(Dwnpoint);
                    TotalLength += SegmentLength;
                }
                break;
            }


            #endregion
        }
Example #38
0
        private void axMapcontrol_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
        {
            sMapunits            = GetMapunits(this.axMapcontrol.Map.MapUnits);
            this.barCoortxt.Text = string.Format("当前坐标:X={0:#.###} Y={1:#.###} {2}", e.mapX, e.mapY, sMapunits);
            movepnt = new PointClass();
            movepnt.PutCoords(e.mapX, e.mapY);
            switch (pMouseOperate)
            {
            case "MeasureLength":
                if (m_newline != null && movepnt != null)
                {
                    m_newline.MoveTo(movepnt);
                    //计算两点距离
                    double deltaX = 0;
                    double deltaY = 0;
                    deltaX        = movepnt.X - Dwnpoint.X;
                    deltaY        = movepnt.Y - Dwnpoint.Y;
                    SegmentLength = Math.Round(Math.Sqrt(deltaX * deltaX + deltaY * deltaY));
                    TotalLength   = TotalLength + SegmentLength;
                    if (frmMeasureResult != null)
                    {
                        //绑定事件
                        ShowResultEvent += new showResult(frmMeasureResult.showResult);
                        ShowResultEvent(new double[] { SegmentLength, TotalLength }, sMapunits, pMouseOperate);
                        TotalLength = TotalLength - SegmentLength;    //鼠标移动到新点重新开始算
                    }
                }
                break;

            case "MeasureArea":
                if (m_newpolygon != null && Area_Pocoll != null)
                {
                    m_newpolygon.MoveTo(movepnt);
                    IPointCollection     pocoll  = new PolygonClass();
                    IGeometry            pGeo    = null;
                    IPolygon             polygon = null;
                    ITopologicalOperator topo    = null;
                    for (int i = 0; i < Area_Pocoll.PointCount; i++)
                    {
                        pocoll.AddPoint(Area_Pocoll.get_Point(i), missing, missing);
                    }
                    if (movepnt == null || movepnt.IsEmpty)
                    {
                        return;
                    }
                    pocoll.AddPoint(movepnt, missing, missing);
                    if (pocoll.PointCount < 3)
                    {
                        return;
                    }
                    polygon = pocoll as IPolygon;
                    if (polygon == null)
                    {
                        return;
                    }
                    //多边形闭合
                    polygon.Close();
                    pGeo = polygon as IGeometry;
                    topo = pGeo as ITopologicalOperator;
                    //使几何图形的拓扑正确
                    topo.Simplify();
                    pGeo.Project(this.axMapcontrol.SpatialReference);
                    IArea area = pGeo as IArea;
                    if (frmMeasureResult != null && !frmMeasureResult.IsDisposed)
                    {
                        ShowResultEvent += new showResult(frmMeasureResult.showResult);
                        ShowResultEvent(new double[] { area.Area, polygon.Length }, sMapunits, pMouseOperate);
                    }
                }
                break;
            }
        }
Example #39
0
        //
        //输出外环面 shape
        public bool OutPutPolygonExteriorRing(IFeatureClass featclass, string outShapeFilePath, bool IsGetExtRingOfHaveInnerRing)
        {
            bool rbc = false;

            if (System.IO.File.Exists(outShapeFilePath) == true)
            {   //输出Shape文件
                LocalShapeFileOperator delshpOp = new LocalShapeFileOperator();
                delshpOp.LocalShapePathFileName = outShapeFilePath;
                delshpOp.DeleteShapeFile();
                delshpOp.Dispose();
            }

            esriGeometryType geoType = featclass.ShapeType;

            //创建新的Shape文件
            LocalShapeFileOperator shpOp = new LocalShapeFileOperator();

            shpOp.LocalShapePathFileName = outShapeFilePath;

            string dir  = shpOp.getDir(outShapeFilePath);
            string name = shpOp.getFileName(outShapeFilePath);
            ShapefileWorkspaceFactoryClass objwsf = new ShapefileWorkspaceFactoryClass();
            IWorkspace        objws    = objwsf.OpenFromFile(dir, 0);
            IFeatureWorkspace feaureWS = objws as IFeatureWorkspace;
            //设置投影
            ISpatialReference sr = (featclass as IGeoDataset).SpatialReference;

            shpOp.ShapeSpatialReference = sr;
            //设置shp文件的oid字段和几何字段
            if (IsObjGeo == false)
            {
                if (featclass.HasOID == true)
                {
                    this.OIDFieldName = featclass.OIDFieldName;
                }
                this.GeometryFieldName = featclass.ShapeFieldName;
            }
            shpOp.OIDFieldName      = this.OIDFieldName;
            shpOp.GeometryFieldName = this.GeometryFieldName;
            //创建要素类
            IFeatureClass fc = shpOp.CreateFeatureClass(feaureWS, name, esriFeatureType.esriFTSimple, geoType);

            if (fc != null)
            {
                TokayWorkspace.ComRelease(fc);
                fc  = null;
                rbc = true;
            }
            TokayWorkspace.ComRelease(objws);
            feaureWS = null;
            objws    = null;
            objwsf   = null;
            //拷贝字段结构
            IFeatureClass  Dfeatclass   = shpOp.getIFeatureClass();
            ZhFeatureClass Szhfeatclass = new ZhPointFeatureClass(featclass);

            Szhfeatclass.CopyFieldsToObjectFeatureClass(Dfeatclass);

            //拷贝几何对象和属性数据
            ZhFeature      Szhfeat       = null;
            IFeatureBuffer DfeatBuffer   = null;
            IFeatureCursor featCurInsert = Dfeatclass.Insert(true);

            //获取总要素个数
            int             fIndex    = 0;
            int             tmpFCount = Szhfeatclass.FeatureClass.FeatureCount(null);
            frmProgressBar1 pb        = new frmProgressBar1();

            pb.Text                 = "正在输出shp文件...";
            pb.Caption1.Text        = "正在输出shp文件...";
            pb.progressBar1.Maximum = tmpFCount + 1;
            pb.progressBar1.Value   = 0;
            pb.Show(this.ParentForm);
            Application.DoEvents();

            object   refobj = Type.Missing;
            IPolygon s_p    = null;

            IRing[] ExtRingArray   = null;
            IRing[] InnerRingArray = null;


            IFeatureCursor featcur = Szhfeatclass.FeatureClass.Search(null, false);
            IFeature       feat    = featcur.NextFeature();

            while (feat != null)
            {
                fIndex += 1;
                if (fIndex % 200 == 0)
                {
                    pb.Caption1.Text      = "已输出要素个数:" + fIndex.ToString() + "/总" + tmpFCount.ToString();
                    pb.progressBar1.Value = fIndex;
                    Application.DoEvents();
                    featCurInsert.Flush();
                }
                s_p = feat.ShapeCopy as IPolygon;
                //获取外环面几何对象
                ExtRingArray = PolygonHelper.GetExteriorRings(s_p);
                if (ExtRingArray != null && ExtRingArray.Length > 0)
                {
                    foreach (IRing r in ExtRingArray)
                    {
                        if (IsGetExtRingOfHaveInnerRing == true)
                        {
                            InnerRingArray = PolygonHelper.GetInteriorRingsByExterior(r, s_p);
                            if (InnerRingArray != null && InnerRingArray.Length > 0)
                            {   //有内环
                                //外环构面并输出保存
                                DfeatBuffer = Dfeatclass.CreateFeatureBuffer();

                                PolygonClass pclass = new PolygonClass();
                                pclass.AddGeometry(r, ref refobj, ref refobj);
                                pclass.SimplifyPreserveFromTo();
                                pclass.SpatialReference = sr;

                                DfeatBuffer.Shape = pclass;

                                //拷贝属性数据
                                Szhfeat = new ZHFeaturePoint(feat);
                                Szhfeat.CopyField(ref DfeatBuffer);

                                featCurInsert.InsertFeature(DfeatBuffer);
                                //
                            }
                        }
                        else
                        {
                            //外环构面并输出保存
                            DfeatBuffer = Dfeatclass.CreateFeatureBuffer();

                            PolygonClass pclass = new PolygonClass();
                            pclass.AddGeometry(r, ref refobj, ref refobj);
                            pclass.SimplifyPreserveFromTo();
                            pclass.SpatialReference = sr;

                            DfeatBuffer.Shape = pclass;

                            //拷贝属性数据
                            Szhfeat = new ZHFeaturePoint(feat);
                            Szhfeat.CopyField(ref DfeatBuffer);

                            featCurInsert.InsertFeature(DfeatBuffer);
                            //
                        }
                    }
                }
                feat = featcur.NextFeature();
            }
            featCurInsert.Flush();
            TokayWorkspace.ComRelease(featcur);
            featcur = null;
            TokayWorkspace.ComRelease(featCurInsert);
            featCurInsert = null;
            rbc           = true;

            pb.Close();
            pb.Dispose();
            pb = null;

            return(rbc);
        }
Example #40
0
        /// <summary>
        /// Saves the file to a new location
        /// </summary>
        /// <param name="fileName">The fileName to save</param>
        /// <param name="overwrite">Boolean that specifies whether or not to overwrite the existing file</param>
        public override void SaveAs(string fileName, bool overwrite)
        {
            EnsureValidFileToSave(fileName, overwrite);
            Filename = fileName;

            // Set ShapeType before setting extent.
            if (CoordinateType == CoordinateType.Regular)
            {
                Header.ShapeType = ShapeType.Polygon;
            }
            if (CoordinateType == CoordinateType.M)
            {
                Header.ShapeType = ShapeType.PolygonM;
            }
            if (CoordinateType == CoordinateType.Z)
            {
                Header.ShapeType = ShapeType.PolygonZ;
            }
            HeaderSaveAs(fileName);

            if (IndexMode)
            {
                SaveAsIndexed(fileName);
                return;
            }

            var bbWriter      = new BufferedBinaryWriter(fileName);
            var indexWriter   = new BufferedBinaryWriter(Header.ShxFilename);
            int fid           = 0;
            int offset        = 50; // the shapefile header starts at 100 bytes, so the initial offset is 50 words
            int contentLength = 0;

            foreach (IFeature f in Features)
            {
                List <int> parts = new List <int>();

                offset += contentLength; // adding the previous content length from each loop calculates the word offset
                List <Coordinate> points = new List <Coordinate>();
                contentLength = 22;
                for (int iPart = 0; iPart < f.Geometry.NumGeometries; iPart++)
                {
                    parts.Add(points.Count);
                    IPolygon pg = f.Geometry.GetGeometryN(iPart) as IPolygon;
                    if (pg == null)
                    {
                        continue;
                    }
                    ILineString bl = pg.Shell;
                    IEnumerable <Coordinate> coords = bl.Coordinates;

                    if (CGAlgorithms.IsCCW(bl.Coordinates))
                    {
                        // Exterior rings need to be clockwise
                        coords = coords.Reverse();
                    }

                    foreach (Coordinate coord in coords)
                    {
                        points.Add(coord);
                    }
                    foreach (ILineString hole in pg.Holes)
                    {
                        parts.Add(points.Count);
                        IEnumerable <Coordinate> holeCoords = hole.Coordinates;
                        if (!CGAlgorithms.IsCCW(hole.Coordinates))
                        {
                            // Interior rings need to be counter-clockwise
                            holeCoords = holeCoords.Reverse();
                        }
                        foreach (Coordinate coord in holeCoords)
                        {
                            points.Add(coord);
                        }
                    }
                }
                contentLength += 2 * parts.Count;
                if (Header.ShapeType == ShapeType.Polygon)
                {
                    contentLength += points.Count * 8;
                }
                if (Header.ShapeType == ShapeType.PolygonM)
                {
                    contentLength += 8;                 // mmin mmax
                    contentLength += points.Count * 12; // x, y, m
                }
                if (Header.ShapeType == ShapeType.PolygonZ)
                {
                    contentLength += 16;                // mmin, mmax, zmin, zmax
                    contentLength += points.Count * 16; // x, y, m, z
                }

                //                                              Index File
                //                                              ---------------------------------------------------------
                //                                              Position     Value               Type        Number      Byte Order
                //                                              ---------------------------------------------------------
                indexWriter.Write(offset, false);               // Byte 0     Offset             Integer     1           Big
                indexWriter.Write(contentLength, false);        // Byte 4    Content Length      Integer     1           Big

                //                                              X Y Poly Lines
                //                                              ---------------------------------------------------------
                //                                              Position     Value               Type        Number      Byte Order
                //                                              ---------------------------------------------------------
                bbWriter.Write(fid + 1, false);              // Byte 0       Record Number       Integer     1           Big
                bbWriter.Write(contentLength, false);        // Byte 4       Content Length      Integer     1           Big
                bbWriter.Write((int)Header.ShapeType);       // Byte 8       Shape Type 3        Integer     1           Little
                if (Header.ShapeType == ShapeType.NullShape)
                {
                    continue;
                }

                bbWriter.Write(f.Geometry.EnvelopeInternal.MinX); // Byte 12      Xmin                Double      1           Little
                bbWriter.Write(f.Geometry.EnvelopeInternal.MinY); // Byte 20      Ymin                Double      1           Little
                bbWriter.Write(f.Geometry.EnvelopeInternal.MaxX); // Byte 28      Xmax                Double      1           Little
                bbWriter.Write(f.Geometry.EnvelopeInternal.MaxY); // Byte 36      Ymax                Double      1           Little
                bbWriter.Write(parts.Count);                      // Byte 44      NumParts            Integer     1           Little
                bbWriter.Write(points.Count);                     // Byte 48      NumPoints           Integer     1           Little
                // Byte 52      Parts               Integer     NumParts    Little
                foreach (int iPart in parts)
                {
                    bbWriter.Write(iPart);
                }
                double[] xyVals = new double[points.Count * 2];

                int i = 0;

                // Byte X       Points              Point       NumPoints   Little
                foreach (Coordinate coord in points)
                {
                    xyVals[i * 2]     = coord.X;
                    xyVals[i * 2 + 1] = coord.Y;
                    i++;
                }
                bbWriter.Write(xyVals);

                if (Header.ShapeType == ShapeType.PolygonZ)
                {
                    bbWriter.Write(f.Geometry.EnvelopeInternal.Minimum.Z);
                    bbWriter.Write(f.Geometry.EnvelopeInternal.Maximum.Z);
                    double[] zVals = new double[points.Count];
                    for (int ipoint = 0; ipoint < points.Count; i++)
                    {
                        zVals[ipoint] = points[ipoint].Z;
                        ipoint++;
                    }
                    bbWriter.Write(zVals);
                }

                if (Header.ShapeType == ShapeType.PolygonM || Header.ShapeType == ShapeType.PolygonZ)
                {
                    if (f.Geometry.EnvelopeInternal == null)
                    {
                        bbWriter.Write(0.0);
                        bbWriter.Write(0.0);
                    }
                    else
                    {
                        bbWriter.Write(f.Geometry.EnvelopeInternal.Minimum.M);
                        bbWriter.Write(f.Geometry.EnvelopeInternal.Maximum.M);
                    }

                    double[] mVals = new double[points.Count];
                    for (int ipoint = 0; ipoint < points.Count; i++)
                    {
                        mVals[ipoint] = points[ipoint].M;
                        ipoint++;
                    }
                    bbWriter.Write(mVals);
                }

                fid++;
                offset += 4; // header bytes
            }

            bbWriter.Close();
            indexWriter.Close();

            offset += contentLength;
            //offset += 4;
            WriteFileLength(fileName, offset);
            WriteFileLength(Header.ShxFilename, 50 + fid * 4);
            UpdateAttributes();
            SaveProjection();
        }
Example #41
0
        private void MapSelectByGeometry()
        {
            // axMapControl1.Map.ClearSelection();
            IMap pMap = axMapControl1.Map;

            if (axMapControl1.Map.LayerCount == 0)
            {
                return;
            }
            if (pMap.LayerCount == 0)
            {
                return;
            }
            // pMap.FeatureSelection.Clear();
            //IFeatureSelection pFeatureSelection = m_CurSelLayer as IFeatureSelection;
            //ISpatialFilter pSpatialFilter = new SpatialFilterClass();
            //pSpatialFilter.SearchOrder = esriSearchOrder.esriSearchOrderSpatial;

            IPolygon pGeometry = null;

            switch (m_CurMapOperation)
            {
            case MapOperation.MapSelectByRect:
            {
                //pGeometry = axMapControl1.TrackRectangle();
                IEnvelope env = axMapControl1.TrackRectangle();        //Track产生envelope
                if (env.Width > 0.5)
                {
                    axMapControl1.Map.ClearSelection();
                    EnvelopeToPolygon(env);          //把Envelope变为Polygon
                    pGeometry = polygon;
                }
                else        //基本可以判断为是点击动作
                {
                    return;
                }
            }
            break;

            case MapOperation.MapPolygonSelect:
            {
                axMapControl1.Map.ClearSelection();
                pGeometry = axMapControl1.TrackPolygon() as IPolygon;          //Track产生Polygon
            }
            break;

            case MapOperation.MapCircleSelect:
            {
                axMapControl1.Map.ClearSelection();
                pGeometry = axMapControl1.TrackCircle() as IPolygon;          //Track产生Circle
            }
            break;
            }
            if (pGeometry == null || pGeometry.Length == 0)
            {
                return;
            }
            //m_pMainform.ShowInfo(pGeometry,false);
            ////MainForm.g_pTrackGeometry = pGeometry as IPolygon;   //把拖拽产生的图形传给CustomStatistics窗口
            //pSpatialFilter.Geometry = pGeometry;
            //pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
            //pFeatureSelection.SelectFeatures(pSpatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
            //axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, axMapControl1.Extent);
            ////axMapControl1.ActiveView.Refresh();
        }
Example #42
0
    private void DrawPolygon(Graphics graphics, IPolygon polygon, Brush brush, Pen bufferPen, Pen pen)
    {
        IPolygon imagePolygon = _transform.ReverseTransform(polygon);

        if (brush != null)
        {
            int numPoints = imagePolygon.ExteriorRing.Coordinates.Length;

            if (imagePolygon.InteriorRings != null && imagePolygon.InteriorRings.Length > 0)
            {
                foreach (ILineString lineString in imagePolygon.InteriorRings)
                {
                    numPoints += lineString.Coordinates.Length + 1;
                }
            }

            PointF[] points = new PointF[numPoints];

            for (int i = 0; i < imagePolygon.ExteriorRing.Coordinates.Length; ++i)
            {
                points[i].X = Convert.ToSingle(imagePolygon.ExteriorRing.Coordinates[i].X * _resolution);
                points[i].Y = Convert.ToSingle(imagePolygon.ExteriorRing.Coordinates[i].Y * _resolution);
            }

            if (imagePolygon.InteriorRings != null && imagePolygon.InteriorRings.Length > 0)
            {
                int offset = imagePolygon.ExteriorRing.Coordinates.Length;

                foreach (ILineString lineString in imagePolygon.InteriorRings)
                {
                    for (int i = 0; i < lineString.Coordinates.Length; ++i)
                    {
                        points[i + offset].X = Convert.ToSingle(lineString.Coordinates[i].X * _resolution);
                        points[i + offset].Y = Convert.ToSingle(lineString.Coordinates[i].Y * _resolution);
                    }

                    offset += lineString.Coordinates.Length;

                    points[offset].X = Convert.ToSingle(imagePolygon.ExteriorRing.Coordinates[0].X * _resolution);
                    points[offset].Y = Convert.ToSingle(imagePolygon.ExteriorRing.Coordinates[0].Y * _resolution);

                    ++offset;
                }
            }

            graphics.FillPolygon(brush, points);
        }

        if (pen == null && bufferPen != null && imagePolygon.EnvelopeInternal.Width < 10 && imagePolygon.EnvelopeInternal.Height < 10)
        {
            pen = bufferPen;
        }

        if (pen != null)
        {
            DrawLineString(graphics, polygon.ExteriorRing, pen);

            foreach (ILineString lineString in polygon.InteriorRings)
            {
                DrawLineString(graphics, lineString, pen);
            }
        }
    }
Example #43
0
 private void DrawPolygon(Graphics graphics, IPolygon polygon, Brush brush, Pen bufferPen)
 {
     DrawPolygon(graphics, polygon, brush, bufferPen, null);
 }
Example #44
0
 private void DrawPolygon(Graphics graphics, IPolygon polygon, Brush brush)
 {
     DrawPolygon(graphics, polygon, brush, null, null);
 }
Example #45
0
 public void PolygonSnapFreeAtObject(ref double minDistance, ref SnapResult snapResult, IPolygon polygon, Coordinate worldPos)
 {
     for (int i = 1; i < polygon.Coordinates.Length; i++)
     {
         Coordinate c1       = polygon.Coordinates[i - 1];
         Coordinate c2       = polygon.Coordinates[i];
         double     distance = GeometryHelper.LinePointDistance(c1.X, c1.Y, c2.X, c2.Y,
                                                                worldPos.X, worldPos.Y);
         if (distance >= minDistance)
         {
             continue;
         }
         minDistance = distance;
         Coordinate min_c1 = polygon.Coordinates[i - 1];
         Coordinate min_c2 = polygon.Coordinates[i];
         snapResult = new SnapResult(GeometryHelper.NearestPointAtSegment(min_c1.X, min_c1.Y,
                                                                          min_c2.X, min_c2.Y, worldPos.X,
                                                                          worldPos.Y), null, null, polygon, i - 1, i)
         {
             Rule = this
         };
     }
 }
Example #46
0
        void axRenderControl1_RcMouseClickSelect(IPickResult PickResult, IPoint IntersectPoint, gviModKeyMask Mask, gviMouseSelectMode EventSender)
        {
            if (PickResult.Type == gviObjectType.gviObjectLabel)
            {
                ILabelPickResult tlpr = PickResult as ILabelPickResult;
                gviObjectType    type = tlpr.Type;
                ILabel           fl   = tlpr.Label;
                MessageBox.Show("拾取到" + type + "类型,内容为" + fl.Text);
            }
            else if (PickResult.Type == gviObjectType.gviObjectRenderModelPoint)
            {
                IRenderModelPointPickResult tlpr = PickResult as IRenderModelPointPickResult;
                gviObjectType     type           = tlpr.Type;
                IRenderModelPoint fl             = tlpr.ModelPoint;
                MessageBox.Show("拾取到" + type + "类型,模型名称为" + fl.ModelName);
            }
            else if (PickResult.Type == gviObjectType.gviObjectRenderPoint)
            {
                IRenderPointPickResult tlpr = PickResult as IRenderPointPickResult;
                gviObjectType          type = tlpr.Type;
                IRenderPoint           fl   = tlpr.Point;
                MessageBox.Show("拾取到" + type + "类型,大小为" + fl.Symbol.Size);
            }
            else if (PickResult.Type == gviObjectType.gviObjectRenderPolyline)
            {
                IRenderPolylinePickResult tlpr = PickResult as IRenderPolylinePickResult;
                gviObjectType             type = tlpr.Type;
                IRenderPolyline           fl   = tlpr.Polyline;
                MessageBox.Show("拾取到" + type + "类型,GUID为" + fl.Guid);
            }
            else if (PickResult.Type == gviObjectType.gviObjectRenderPolygon)
            {
                IRenderPolygonPickResult tlpr = PickResult as IRenderPolygonPickResult;
                gviObjectType            type = tlpr.Type;
                IRenderPolygon           fl   = tlpr.Polygon;
                MessageBox.Show("拾取到" + type + "类型,GUID为" + fl.Guid);
            }
            else if (PickResult.Type == gviObjectType.gviObjectRenderPOI)
            {
                IRenderPOIPickResult tlpr = PickResult as IRenderPOIPickResult;
                gviObjectType        type = tlpr.Type;
                IRenderPOI           fl   = tlpr.POI;
                MessageBox.Show("拾取到" + type + "类型,名称为" + ((IPOI)fl.GetFdeGeometry()).Name);
            }
            else if (PickResult.Type == gviObjectType.gviObjectTerrainRegularPolygon)
            {
                ITerrainRegularPolygonPickResult regPolygonPick = PickResult as ITerrainRegularPolygonPickResult;
                gviObjectType          type       = regPolygonPick.Type;
                ITerrainRegularPolygon regPolygon = regPolygonPick.TerrainRegularPolygon;
                MessageBox.Show("拾取到" + type + "类型,geometryCount为" + regPolygon.GetFdeGeometry().GeometryType);
            }
            else if (PickResult.Type == gviObjectType.gviObjectTerrainArrow)
            {
                ITerrainArrowPickResult arrowPickResult = PickResult as ITerrainArrowPickResult;
                gviObjectType           type            = arrowPickResult.Type;
                ITerrainArrow           arrow           = arrowPickResult.TerrainArrow;
                MessageBox.Show("拾取到" + type + "类型,geometryType" + arrow.GetFdeGeometry().GeometryType);
            }
            else if (PickResult.Type == gviObjectType.gviObjectReferencePlane)
            {
                switch (this.toolStripComboBoxObjectManager.Text)
                {
                case "CreateLabel":
                {
                    label                     = this.axRenderControl1.ObjectManager.CreateLabel(rootId);
                    label.Text                = "我是testlabel";
                    label.Position            = IntersectPoint;
                    textSymbol                = new TextSymbol();
                    textAttribute             = new TextAttribute();
                    textAttribute.TextColor   = System.Drawing.Color.Yellow;
                    textAttribute.TextSize    = 20;
                    textAttribute.Underline   = true;
                    textAttribute.Font        = "楷体";
                    textSymbol.TextAttribute  = textAttribute;
                    textSymbol.VerticalOffset = 10;
                    textSymbol.DrawLine       = true;
                    textSymbol.MarginColor    = System.Drawing.Color.Yellow;
                    label.TextSymbol          = textSymbol;
                    this.axRenderControl1.Camera.FlyToObject(label.Guid, gviActionCode.gviActionFlyTo);
                }
                break;

                case "CreateRenderModelPoint":
                {
                    if (gfactory == null)
                    {
                        gfactory = new GeometryFactory();
                    }

                    string tmpOSGPath = (strMediaPath + @"\osg\Buildings\Apartment\Apartment.osg");
                    fde_modelpoint = gfactory.CreateGeometry(gviGeometryType.gviGeometryModelPoint,
                                                             gviVertexAttribute.gviVertexAttributeZ) as IModelPoint;
                    fde_modelpoint.SetCoords(IntersectPoint.X, IntersectPoint.Y, IntersectPoint.Z, 0, 0);
                    fde_modelpoint.ModelName = tmpOSGPath;
                    rmodelpoint = this.axRenderControl1.ObjectManager.CreateRenderModelPoint(fde_modelpoint, null, rootId);
                    rmodelpoint.MaxVisibleDistance = double.MaxValue;
                    rmodelpoint.MinVisiblePixels   = 0;
                    rmodelpoint.ShowOutline        = checkShowOutline.Checked;
                    IEulerAngle angle = new EulerAngle();
                    angle.Set(0, -20, 0);
                    this.axRenderControl1.Camera.LookAt(IntersectPoint.Position, 100, angle);
                }
                break;

                case "CreateRenderPoint":
                {
                    if (gfactory == null)
                    {
                        gfactory = new GeometryFactory();
                    }

                    fde_point = (IPoint)gfactory.CreateGeometry(gviGeometryType.gviGeometryPoint,
                                                                gviVertexAttribute.gviVertexAttributeZ);
                    fde_point.SetCoords(IntersectPoint.X, IntersectPoint.Y, IntersectPoint.Z, 0, 0);

                    pointSymbol           = new SimplePointSymbol();
                    pointSymbol.FillColor = System.Drawing.Color.Red;
                    pointSymbol.Size      = 10;
                    rpoint             = this.axRenderControl1.ObjectManager.CreateRenderPoint(fde_point, pointSymbol, rootId);
                    rpoint.ShowOutline = checkShowOutline.Checked;
                    this.axRenderControl1.Camera.FlyToObject(rpoint.Guid, gviActionCode.gviActionFlyTo);
                }
                break;

                case "CreateRenderPolyline":
                {
                    if (gfactory == null)
                    {
                        gfactory = new GeometryFactory();
                    }

                    fde_polyline = (IPolyline)gfactory.CreateGeometry(gviGeometryType.gviGeometryPolyline,
                                                                      gviVertexAttribute.gviVertexAttributeZ);
                    fde_point = (IPoint)gfactory.CreateGeometry(gviGeometryType.gviGeometryPoint,
                                                                gviVertexAttribute.gviVertexAttributeZ);
                    fde_point.SetCoords(IntersectPoint.X, IntersectPoint.Y, IntersectPoint.Z, 0, 0);
                    fde_polyline.AppendPoint(fde_point);
                    fde_point.SetCoords(IntersectPoint.X + 20, IntersectPoint.Y, IntersectPoint.Z, 0, 0);
                    fde_polyline.AppendPoint(fde_point);
                    fde_point.SetCoords(IntersectPoint.X + 20, IntersectPoint.Y + 20, IntersectPoint.Z, 0, 0);
                    fde_polyline.AppendPoint(fde_point);
                    fde_point.SetCoords(IntersectPoint.X + 20, IntersectPoint.Y + 20, IntersectPoint.Z + 20, 0, 0);
                    fde_polyline.AppendPoint(fde_point);

                    lineSymbol            = new CurveSymbol();
                    lineSymbol.Color      = System.Drawing.Color.Red;     // 紫红色
                    rpolyline             = this.axRenderControl1.ObjectManager.CreateRenderPolyline(fde_polyline, lineSymbol, rootId);
                    rpolyline.ShowOutline = checkShowOutline.Checked;
                    this.axRenderControl1.Camera.FlyToObject(rpolyline.Guid, gviActionCode.gviActionFlyTo);
                }
                break;

                case "CreateRenderPolygon":
                {
                    if (gfactory == null)
                    {
                        gfactory = new GeometryFactory();
                    }

                    fde_polygon = (IPolygon)gfactory.CreateGeometry(gviGeometryType.gviGeometryPolygon,
                                                                    gviVertexAttribute.gviVertexAttributeZ);

                    fde_point = (IPoint)gfactory.CreateGeometry(gviGeometryType.gviGeometryPoint,
                                                                gviVertexAttribute.gviVertexAttributeZ);
                    fde_point.SetCoords(IntersectPoint.X, IntersectPoint.Y, IntersectPoint.Z, 0, 0);
                    fde_polygon.ExteriorRing.AppendPoint(fde_point);
                    fde_point.SetCoords(IntersectPoint.X + 10, IntersectPoint.Y, IntersectPoint.Z, 0, 0);
                    fde_polygon.ExteriorRing.AppendPoint(fde_point);
                    fde_point.SetCoords(IntersectPoint.X + 10, IntersectPoint.Y + 10, IntersectPoint.Z, 0, 0);
                    fde_polygon.ExteriorRing.AppendPoint(fde_point);
                    fde_point.SetCoords(IntersectPoint.X, IntersectPoint.Y + 10, IntersectPoint.Z, 0, 0);
                    fde_polygon.ExteriorRing.AppendPoint(fde_point);

                    surfaceSymbol        = new SurfaceSymbol();
                    surfaceSymbol.Color  = System.Drawing.Color.Blue;         // 蓝色
                    rpolygon             = this.axRenderControl1.ObjectManager.CreateRenderPolygon(fde_polygon, surfaceSymbol, rootId);
                    rpolygon.ShowOutline = checkShowOutline.Checked;
                    this.axRenderControl1.Camera.FlyToObject(rpolygon.Guid, gviActionCode.gviActionFlyTo);
                }
                break;

                case "CreateRenderPOI":
                {
                    if (gfactory == null)
                    {
                        gfactory = new GeometryFactory();
                    }

                    fde_poi = (IPOI)gfactory.CreateGeometry(gviGeometryType.gviGeometryPOI, gviVertexAttribute.gviVertexAttributeZ);
                    fde_poi.SetCoords(IntersectPoint.X, IntersectPoint.Y, IntersectPoint.Z, 0, 0);
                    fde_poi.ImageName = "#(1)";
                    fde_poi.Name      = (++poiCount).ToString();
                    fde_poi.Size      = 50;
                    rpoi             = this.axRenderControl1.ObjectManager.CreateRenderPOI(fde_poi);
                    rpoi.ShowOutline = checkShowOutline.Checked;
                    this.axRenderControl1.Camera.FlyToObject(rpoi.Guid, gviActionCode.gviActionFlyTo);
                }
                break;

                case "CreateFixedBillboard":
                {
                    TextAttribute ta = new TextAttribute();
                    ta.TextSize  = 10;
                    ta.TextColor = System.Drawing.Color.Yellow;
                    IImage image     = null;
                    IModel model     = null;
                    string imageName = "";
                    this.axRenderControl1.Utility.CreateFixedBillboard("I'm fixed billboard!", ta, 50, 100, true, out model, out image, out imageName);
                    this.axRenderControl1.ObjectManager.AddModel("fixedModel", model);
                    this.axRenderControl1.ObjectManager.AddImage(imageName, image);

                    if (gfactory == null)
                    {
                        gfactory = new GeometryFactory();
                    }
                    fde_modelpoint = gfactory.CreateGeometry(gviGeometryType.gviGeometryModelPoint,
                                                             gviVertexAttribute.gviVertexAttributeZ) as IModelPoint;
                    fde_modelpoint.SetCoords(IntersectPoint.X, IntersectPoint.Y, IntersectPoint.Z, 0, 0);
                    fde_modelpoint.ModelName = "fixedModel";
                    rmodelpoint = this.axRenderControl1.ObjectManager.CreateRenderModelPoint(fde_modelpoint, null, rootId);
                    rmodelpoint.MaxVisibleDistance = double.MaxValue;
                    rmodelpoint.MinVisiblePixels   = 0;
                    rmodelpoint.ShowOutline        = checkShowOutline.Checked;
                    IEulerAngle angle = new EulerAngle();
                    angle.Set(0, -20, 0);
                    this.axRenderControl1.Camera.LookAt(IntersectPoint.Position, 100, angle);
                }
                break;

                case "CreateRegularPolygon":
                {
                    IPosition pos = new Position();
                    pos.X        = IntersectPoint.X;
                    pos.Y        = IntersectPoint.Y;
                    pos.Altitude = IntersectPoint.Z;
                    ITerrainRegularPolygon regPolygon = this.axRenderControl1.ObjectManager.CreateRegularPolygon(pos, 10, 10, System.Drawing.Color.Red, System.Drawing.Color.White, rootId);
                    this.axRenderControl1.Camera.FlyToObject(regPolygon.Guid, gviActionCode.gviActionFlyTo);
                }
                break;

                case "CreateArrow":
                {
                    IPosition pos = new Position();
                    pos.X        = IntersectPoint.X;
                    pos.Y        = IntersectPoint.Y;
                    pos.Altitude = IntersectPoint.Z;
                    ITerrainArrow regArrow = this.axRenderControl1.ObjectManager.CreateArrow(pos, 30, 4, System.Drawing.Color.Red, System.Drawing.Color.White, rootId);
                    this.axRenderControl1.Camera.FlyToObject(regArrow.Guid, gviActionCode.gviActionFlyTo);
                }
                break;
                }
            }
        }
Example #47
0
 public void PolygonSnapFree(ref double minDistance, ref SnapResult snapResult, IPolygon polygon, Coordinate worldPos)
 {
     for (int i = 1; i < polygon.Coordinates.Length; i++)
     {
         Coordinate c1       = polygon.Coordinates[i - 1];
         Coordinate c2       = polygon.Coordinates[i];
         double     distance = GeometryHelper.LinePointDistance(c1.X, c1.Y, c2.X, c2.Y, worldPos.X, worldPos.Y);
         if (distance >= minDistance)
         {
             continue;
         }
         minDistance = distance;
         snapResult  = new SnapResult(GeometryFactoryEx.CreateCoordinate(worldPos.X, worldPos.Y), null, null, polygon,
                                      i - 1, i)
         {
             Rule = this
         };
     }
 }
Example #48
0
        private void PolygonExpand(int count, int span)
        {
            if (_alpha == 0)
            {
                return;
            }
            int num = 25;

            for (int i = 0; i < count; i++)
            {
                double[] numArray = _elipse.drawElipse();
                _elipse.timeSpan += span;
                if (numArray != null && numArray.Length > 0)
                {
                    List <IPoint> list = new List <IPoint>();
                    for (int j = 0; j < ((numArray.Length / 2) - 1); j++)
                    {
                        if (numArray[j * 2] == double.NaN)
                        {
                            break;
                        }
                        IPoint item = (new GeometryFactory()).CreatePoint(gviVertexAttribute.gviVertexAttributeZ);
                        item.X = numArray[j * 2];
                        item.Y = numArray[(j * 2) + 1];
                        item.Z = num; //0.0 25
                        list.Add(item);
                        if (j == ((numArray.Length / 2) - 2))
                        {
                            list.Add(list[0]);
                        }
                    }
                    if (list.Count > 0)
                    {
                        IPolygon geometry = (new GeometryFactory()).CreateGeometry(gviGeometryType.gviGeometryPolygon, gviVertexAttribute.gviVertexAttributeZ) as IPolygon;
                        for (int k = 0; k < list.Count; k++)
                        {
                            geometry.ExteriorRing.AppendPoint(list[k]);
                        }
                        IPolygon fdeValue = null;
                        IPolygon polygon3 = null;
                        if (i == 0)
                        {
                            polygon3 = geometry;
                        }
                        else if (_oldGeo != null)
                        {
                            polygon3 = (geometry as ITopologicalOperator2D).SymmetricDifference2D(_oldGeo) as IPolygon;
                            if (polygon3 != null)
                            {
                                fdeValue = (new GeometryFactory()).CreateGeometry(gviGeometryType.gviGeometryPolygon, gviVertexAttribute.gviVertexAttributeZ) as IPolygon;
                                for (int m = 0; m < polygon3.ExteriorRing.PointCount; m++)
                                {
                                    IPoint point      = polygon3.ExteriorRing.GetPoint(m);
                                    IPoint pointValue = (new GeometryFactory()).CreatePoint(gviVertexAttribute.gviVertexAttributeZ);
                                    pointValue.X = point.X;
                                    pointValue.Y = point.Y;
                                    pointValue.Z = num;
                                    fdeValue.ExteriorRing.AppendPoint(pointValue);
                                }
                            }
                        }
                        else if (polygon3 == null)
                        {
                            _oldGeo = geometry;
                            continue;
                        }
                        if ((polygon3 != null) && (fdeValue != null))
                        {
                            ISurfaceSymbol ss = new SurfaceSymbol();
                            ss.Color = colorFromARGB(_alpha, 255, 0, 0);
                            ICurveSymbol bs = new CurveSymbol();
                            bs.Color          = colorFromARGB(_alpha, 175, 0, 0);
                            ss.BoundarySymbol = bs;
                            IRenderPolygon rPolygon = d3.ObjectManager.CreateRenderPolygon(fdeValue, ss, d3.ProjectTree.RootID);
                            rPolygon.HeightStyle = gviHeightStyle.gviHeightOnTerrain;
                            if (this.ceFlyToRes.Checked)
                            {
                                d3.Camera.FlyToObject(rPolygon.Guid, gviActionCode.gviActionFlyTo);
                            }
                            _renderObjs.Add(rPolygon.Guid);
                            if (_alpha > 0)
                            {
                                _alpha = _alpha - 3;
                            }
                            if (_alpha < 0)
                            {
                                _alpha = 0;
                            }
                        }
                    }
                }
            }
        }
Example #49
0
        private void MapCircleSelect()
        {
            try
            {
                IMap pMap = axMapControl1.Map;
                if (axMapControl1.Map.LayerCount == 0)
                {
                    return;
                }
                if (pMap.LayerCount == 0)
                {
                    return;
                }
                ISelectionEnvironment pSelEnvi = new SelectionEnvironmentClass();
                // IEnvelope pEnv = new EnvelopeClass();pEnv = axMapControl1.TrackCircle();Dim pTopo As
                IPolygon pPolygon = axMapControl1.TrackCircle() as IPolygon;   //获取任意统计口径(圆)
                //MainForm.g_pTrackGeometry = pPolygon;    //获得拖拽圆
                ITopologicalOperator pTopo = pPolygon as ITopologicalOperator;
                pTopo.Simplify();
                pMap.SelectByShape(pPolygon, null, false);
                IEnumLayer pEnumLayer;
                ILayer     pLayer;
                pEnumLayer = pMap.get_Layers(null, true);
                if (pEnumLayer == null)
                {
                    return;
                }
                pEnumLayer.Reset();
                for (pLayer = pEnumLayer.Next(); pLayer != null; pLayer = pEnumLayer.Next())
                {
                    if (pLayer is IFeatureLayer)
                    {
                        IFeatureLayer pFeatureLayer = pLayer as IFeatureLayer;
                        if (pFeatureLayer.Name == m_strCurSelLayer)
                        {
                            continue;
                        }
                        IFeatureSelection ppFeatureSelction = pFeatureLayer as IFeatureSelection;
                        ppFeatureSelction.Clear();
                    }
                }

                ISelection   pFeatureSelction = pMap.FeatureSelection;
                IEnumFeature pEnumFeature     = pFeatureSelction as IEnumFeature;
                IFeature     pFeature         = pEnumFeature.Next();
                IArray       pFArray          = new ArrayClass();
                while (pFeature != null)
                {
                    IObjectClass  pObjectClass  = pFeature.Class;
                    IFeatureClass pFeatureClass = pObjectClass as IFeatureClass;
                    if (pFeatureClass.AliasName == m_strCurSelLayer)
                    {
                        pFArray.Add(pFeature);
                    }


                    pFeature = pEnumFeature.Next();
                }
                axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, axMapControl1.Extent);
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); return; }
        }
Example #50
0
        /// <summary>
        /// This method produces instances of type <see cref="Gisoft.GeoAPI.Geometries.IMultiPolygon"/>.
        /// </summary>
        /// <returns>The created geometries</returns>
        internal override Collection <IGeometry> createGeometries()
        {
            //IMultiPolygon multiPolygon = null;

            IPathNode multiPolygonNode     = new PathNode(_GMLNS, "MultiPolygon", (NameTable)_XmlReader.NameTable);
            IPathNode multiSurfaceNode     = new PathNode(_GMLNS, "MultiSurface", (NameTable)_XmlReader.NameTable);
            IPathNode multiPolygonNodeAlt  = new AlternativePathNodesCollection(multiPolygonNode, multiSurfaceNode);
            IPathNode polygonMemberNode    = new PathNode(_GMLNS, "polygonMember", (NameTable)_XmlReader.NameTable);
            IPathNode surfaceMemberNode    = new PathNode(_GMLNS, "surfaceMember", (NameTable)_XmlReader.NameTable);
            IPathNode polygonMemberNodeAlt = new AlternativePathNodesCollection(polygonMemberNode, surfaceMemberNode);
            IPathNode linearRingNode       = new PathNode(_GMLNS, "LinearRing", (NameTable)_XmlReader.NameTable);
            var       labelValues          = new Dictionary <string, string>();
            bool      geomFound            = false;

            try
            {
                // Reading the entire feature's node makes it possible to collect label values that may appear before or after the geometry property
                while ((_FeatureReader = GetSubReaderOf(_XmlReader, null, _FeatureNode)) != null)
                {
                    while (
                        (_GeomReader =
                             GetSubReaderOf(_FeatureReader, labelValues, multiPolygonNodeAlt)) != null)
                    {
                        XmlReader memberReader;
                        var       polygons = new List <IGeometry>();
                        while ((memberReader = GetSubReaderOf(_GeomReader, labelValues, polygonMemberNodeAlt)) != null)
                        {
                            GeometryFactory geomFactory = new PolygonFactory(memberReader, _FeatureTypeInfo)
                            {
                                AxisOrder = AxisOrder
                            };
                            var polygon = geomFactory.createGeometries()[0]; // polygon element has a maxOccurs=1

                            polygons.Add(polygon);

                            geomFound = true;
                        }

                        if (geomFound)
                        {
                            var polygonArray = new IPolygon[polygons.Count];
                            var i            = 0;
                            foreach (IPolygon polygon in polygons)
                            {
                                polygonArray[i++] = polygon;
                            }

                            _Geoms.Add(Factory.CreateMultiPolygon(polygonArray));
                        }
                    }
                    if (geomFound)
                    {
                        AddLabel(labelValues, _Geoms[_Geoms.Count - 1]);
                    }
                    geomFound = false;
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("An exception occured while parsing a multi-polygon geometry: " + ex.Message);
                throw ex;
            }

            return(_Geoms);
        }
        /// <summary>
        /// Tests each member currently in the selected features based on
        /// the SelectionMode. If it passes, it will remove the feature from
        /// the selection.
        /// </summary>
        /// <param name="region">The geographic region to remove</param>
        /// <param name="affectedArea">A geographic area that was affected by this change.</param>
        /// <returns>Boolean, true if the collection was changed</returns>
        public bool RemoveRegion(Envelope region, out Envelope affectedArea)
        {
            SuspendChanges();
            bool removed = false;

            affectedArea = new Envelope();

            var             query            = from pair in Filter.DrawnStates where pair.Value.IsSelected select pair.Key;
            List <IFeature> selectedFeatures = query.ToList();

            foreach (IFeature f in selectedFeatures)
            {
                bool doRemove = false;
                if (SelectionMode == SelectionMode.IntersectsExtent)
                {
                    if (region.Intersects(f.Geometry.EnvelopeInternal))
                    {
                        if (Remove(f))
                        {
                            removed = true;
                            affectedArea.ExpandToInclude(f.Geometry.EnvelopeInternal);
                        }
                    }
                }
                else if (SelectionMode == SelectionMode.ContainsExtent)
                {
                    if (region.Contains(f.Geometry.EnvelopeInternal))
                    {
                        if (Remove(f))
                        {
                            removed = true;
                            affectedArea.ExpandToInclude(f.Geometry.EnvelopeInternal);
                        }
                    }
                }

                IPolygon  reg  = region.ToPolygon();
                IGeometry geom = f.Geometry;
                switch (SelectionMode)
                {
                case SelectionMode.Contains:
                    if (region.Intersects(f.Geometry.EnvelopeInternal))
                    {
                        if (reg.Contains(geom))
                        {
                            doRemove = true;
                        }
                    }

                    break;

                case SelectionMode.CoveredBy:
                    if (reg.CoveredBy(geom))
                    {
                        doRemove = true;
                    }
                    break;

                case SelectionMode.Covers:
                    if (reg.Covers(geom))
                    {
                        doRemove = true;
                    }
                    break;

                case SelectionMode.Disjoint:
                    if (reg.Disjoint(geom))
                    {
                        doRemove = true;
                    }
                    break;

                case SelectionMode.Intersects:
                    if (region.Intersects(f.Geometry.EnvelopeInternal))
                    {
                        if (reg.Intersects(geom))
                        {
                            doRemove = true;
                        }
                    }

                    break;

                case SelectionMode.Overlaps:
                    if (reg.Overlaps(geom))
                    {
                        doRemove = true;
                    }
                    break;

                case SelectionMode.Touches:
                    if (reg.Touches(geom))
                    {
                        doRemove = true;
                    }
                    break;

                case SelectionMode.Within:
                    if (reg.Within(geom))
                    {
                        doRemove = true;
                    }
                    break;
                }

                if (doRemove)
                {
                    if (Remove(f))
                    {
                        affectedArea.ExpandToInclude(f.Geometry.EnvelopeInternal);
                        removed = true;
                    }
                }
            }

            ResumeChanges();
            return(removed);
        }
Example #52
0
        private void MapPolygonSelect()
        {
            IMap pMap = axMapControl1.Map;

            if (axMapControl1.Map.LayerCount == 0)
            {
                return;
            }
            if (pMap.LayerCount == 0)
            {
                return;
            }
            ISelectionEnvironment pSelEnvi = new SelectionEnvironmentClass();
            IPolygon pPolygon = axMapControl1.TrackPolygon() as IPolygon;
            // MainForm.g_pTrackGeometry = pPolygon;   //获得拖拽多边形形
            ITopologicalOperator pTopo = pPolygon as ITopologicalOperator;

            pTopo.Simplify();
            pMap.SelectByShape(pPolygon, null, false);
            IEnumLayer pEnumLayer;
            ILayer     pLayer;

            pEnumLayer = pMap.get_Layers(null, true);
            if (pEnumLayer == null)
            {
                return;
            }
            pEnumLayer.Reset();
            for (pLayer = pEnumLayer.Next(); pLayer != null; pLayer = pEnumLayer.Next())
            {
                if (pLayer is IFeatureLayer)
                {
                    IFeatureLayer pFeatureLayer = pLayer as IFeatureLayer;
                    if (pFeatureLayer.Name == m_strCurSelLayer)
                    {
                        continue;
                    }
                    IFeatureSelection ppFeatureSelction = pFeatureLayer as IFeatureSelection;
                    ppFeatureSelction.Clear();
                }
            }

            ISelection   pFeatureSelction = pMap.FeatureSelection;
            IEnumFeature pEnumFeature     = pFeatureSelction as IEnumFeature;
            IFeature     pFeature         = pEnumFeature.Next();
            IArray       pFArray          = new ArrayClass();

            while (pFeature != null)
            {
                IObjectClass  pObjectClass  = pFeature.Class;
                IFeatureClass pFeatureClass = pObjectClass as IFeatureClass;
                if (pFeatureClass.AliasName == m_strCurSelLayer)
                {
                    pFArray.Add(pFeature);
                }


                pFeature = pEnumFeature.Next();
            }

            axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, axMapControl1.Extent);
        }
        /// <summary>
        /// Inverts the selection based on the current SelectionMode
        /// </summary>
        /// <param name="region">The geographic region to reverse the selected state</param>
        /// <param name="affectedArea">The affected area to invert</param>
        /// <returns>True, if the selection was changed.</returns>
        public bool InvertSelection(Envelope region, out Envelope affectedArea)
        {
            SuspendChanges();
            bool flipped = false;

            affectedArea = new Envelope();

            IDictionary <IFeature, IDrawnState> states = Filter.DrawnStates;

            foreach (KeyValuePair <IFeature, IDrawnState> kvp in states)
            {
                bool     doFlip = false;
                IFeature f      = kvp.Key;
                if (SelectionMode == SelectionMode.IntersectsExtent)
                {
                    if (region.Intersects(f.Geometry.EnvelopeInternal))
                    {
                        kvp.Value.IsSelected = !kvp.Value.IsSelected;
                        affectedArea.ExpandToInclude(f.Geometry.EnvelopeInternal);
                    }
                }
                else if (SelectionMode == SelectionMode.ContainsExtent)
                {
                    if (region.Contains(f.Geometry.EnvelopeInternal))
                    {
                        kvp.Value.IsSelected = !kvp.Value.IsSelected;
                        affectedArea.ExpandToInclude(f.Geometry.EnvelopeInternal);
                    }
                }

                IPolygon  reg  = region.ToPolygon();
                IGeometry geom = f.Geometry;
                switch (SelectionMode)
                {
                case SelectionMode.Contains:
                    if (region.Intersects(f.Geometry.EnvelopeInternal))
                    {
                        if (reg.Contains(geom))
                        {
                            doFlip = true;
                        }
                    }

                    break;

                case SelectionMode.CoveredBy:
                    if (reg.CoveredBy(geom))
                    {
                        doFlip = true;
                    }
                    break;

                case SelectionMode.Covers:
                    if (reg.Covers(geom))
                    {
                        doFlip = true;
                    }
                    break;

                case SelectionMode.Disjoint:
                    if (reg.Disjoint(geom))
                    {
                        doFlip = true;
                    }
                    break;

                case SelectionMode.Intersects:
                    if (region.Intersects(f.Geometry.EnvelopeInternal))
                    {
                        if (reg.Intersects(geom))
                        {
                            doFlip = true;
                        }
                    }

                    break;

                case SelectionMode.Overlaps:
                    if (reg.Overlaps(geom))
                    {
                        doFlip = true;
                    }
                    break;

                case SelectionMode.Touches:
                    if (reg.Touches(geom))
                    {
                        doFlip = true;
                    }
                    break;

                case SelectionMode.Within:
                    if (reg.Within(geom))
                    {
                        doFlip = true;
                    }
                    break;
                }

                if (doFlip)
                {
                    flipped = true;
                    kvp.Value.IsSelected = !kvp.Value.IsSelected;
                    affectedArea.ExpandToInclude(f.Geometry.EnvelopeInternal);
                }
            }

            ResumeChanges();
            return(flipped);
        }
Example #54
0
 /// <summary>
 /// Triangulates a polygon, applying constraint options.
 /// </summary>
 /// <param name="options">Constraint options.</param>
 public static IMesh Triangulate(this IPolygon polygon, ConstraintOptions options)
 {
     return((new GenericMesher()).Triangulate(polygon, options, null));
 }
Example #55
0
 /// <summary>
 /// Triangulates a polygon, applying quality options.
 /// </summary>
 /// <param name="quality">Quality options.</param>
 public static IMesh Triangulate(this IPolygon polygon, QualityOptions quality)
 {
     return((new GenericMesher()).Triangulate(polygon, null, quality));
 }
Example #56
0
 /// <summary>
 /// Triangulates a polygon, applying quality and constraint options.
 /// </summary>
 /// <param name="options">Constraint options.</param>
 /// <param name="quality">Quality options.</param>
 /// <param name="triangulator">The triangulation algorithm.</param>
 public static IMesh Triangulate(this IPolygon polygon, ConstraintOptions options, QualityOptions quality,
                                 ITriangulator triangulator)
 {
     return((new GenericMesher(triangulator)).Triangulate(polygon, options, quality));
 }
Example #57
0
        private void AddRecord()
        {
            try
            {
                this.beforeRowBufferMap.Clear();
                SelectCollection.Instance().Clear();
                DF3DFeatureClass featureClassInfo = CommonUtils.Instance().CurEditLayer;
                if (featureClassInfo == null)
                {
                    return;
                }
                IFeatureClass fc = featureClassInfo.GetFeatureClass();
                if (fc == null)
                {
                    return;
                }
                IFeatureLayer fl = featureClassInfo.GetFeatureLayer();
                if (fl == null)
                {
                    return;
                }
                IFieldInfoCollection fields = fc.GetFields();
                int indexGeo = fields.IndexOf(fl.GeometryFieldName);
                if (indexGeo == -1)
                {
                    return;
                }
                IFieldInfo fiGeo = fields.Get(indexGeo);
                if (fiGeo == null || fiGeo.GeometryDef == null)
                {
                    return;
                }

                IGeometry geo = this._drawTool.GetGeo();
                if (geo.GeometryType != gviGeometryType.gviGeometryPolygon)
                {
                    return;
                }
                IPolygon polygon = geo as IPolygon;
                IPolygon geoOut  = this._geoFact.CreateGeometry(gviGeometryType.gviGeometryPolygon, fiGeo.GeometryDef.VertexAttribute) as IPolygon;
                for (int i = 0; i < polygon.ExteriorRing.PointCount; i++)
                {
                    IPoint ptGet  = polygon.ExteriorRing.GetPoint(i);
                    IPoint pttemp = ptGet.Clone2(fiGeo.GeometryDef.VertexAttribute) as IPoint;
                    if (fiGeo.GeometryDef.HasZ)
                    {
                        pttemp.SetCoords(ptGet.X, ptGet.Y, ptGet.Z, 0, 0);
                    }
                    else
                    {
                        pttemp.SetCoords(ptGet.X, ptGet.Y, 0, 0, 0);
                    }
                    geoOut.ExteriorRing.AppendPoint(pttemp);
                }

                IRowBufferCollection rowCol = new RowBufferCollection();
                IRowBufferFactory    fac    = new RowBufferFactory();
                IRowBuffer           row    = fac.CreateRowBuffer(fields);
                row.SetValue(indexGeo, geoOut);
                foreach (DataRow dr in this._dt.Rows)
                {
                    IFieldInfo fi = dr["F"] as IFieldInfo;
                    if (fi == null)
                    {
                        continue;
                    }
                    string fn    = fi.Name;
                    int    index = fields.IndexOf(fn);
                    if (index != -1)
                    {
                        if (dr["FV"] == null)
                        {
                            row.SetNull(index);
                        }
                        else
                        {
                            string strobj = dr["FV"].ToString();
                            bool   bRes   = false;
                            switch (fi.FieldType)
                            {
                            case gviFieldType.gviFieldBlob:
                            case gviFieldType.gviFieldGeometry:
                            case gviFieldType.gviFieldUnknown:
                                break;

                            case gviFieldType.gviFieldFloat:
                                float f;
                                bRes = float.TryParse(strobj, out f);
                                if (bRes)
                                {
                                    row.SetValue(index, f);
                                }
                                else
                                {
                                    row.SetNull(index);
                                }
                                break;

                            case gviFieldType.gviFieldDouble:
                                double d;
                                bRes = double.TryParse(strobj, out d);
                                if (bRes)
                                {
                                    row.SetValue(index, d);
                                }
                                else
                                {
                                    row.SetNull(index);
                                }
                                break;

                            case gviFieldType.gviFieldFID:
                            case gviFieldType.gviFieldUUID:
                            case gviFieldType.gviFieldInt16:
                                Int16 i16;
                                bRes = Int16.TryParse(strobj, out i16);
                                if (bRes)
                                {
                                    row.SetValue(index, i16);
                                }
                                else
                                {
                                    row.SetNull(index);
                                }
                                break;

                            case gviFieldType.gviFieldInt32:
                                Int32 i32;
                                bRes = Int32.TryParse(strobj, out i32);
                                if (bRes)
                                {
                                    row.SetValue(index, i32);
                                }
                                else
                                {
                                    row.SetNull(index);
                                }
                                break;

                            case gviFieldType.gviFieldInt64:
                                Int64 i64;
                                bRes = Int64.TryParse(strobj, out i64);
                                if (bRes)
                                {
                                    row.SetValue(index, i64);
                                }
                                else
                                {
                                    row.SetNull(index);
                                }
                                break;;

                            case gviFieldType.gviFieldString:
                                row.SetValue(index, strobj);
                                break;

                            case gviFieldType.gviFieldDate:
                                DateTime dt;
                                bRes = DateTime.TryParse(strobj, out dt);
                                if (bRes)
                                {
                                    row.SetValue(index, dt);
                                }
                                else
                                {
                                    row.SetNull(index);
                                }
                                break;

                            default:
                                break;
                            }
                        }
                    }
                }
                rowCol.Add(row);
                beforeRowBufferMap[featureClassInfo] = rowCol;
                UpdateDatabase();
            }
            catch (Exception ex)
            {
            }
        }
Example #58
0
        private void MapUserIdentify(double mapX, double mapY)
        {
            try
            {
                //axMapControl1.Map.ClearSelection();
                ESRI.ArcGIS.Controls.IMapControl3 m_mapControl = (IMapControl3)axMapControl1.Object;
                IMap        pMap        = axMapControl1.Map;
                IGroupLayer pGroupLayer = new GroupLayer();

                if (pMap.LayerCount == 0)
                {
                    return;
                }
                IEnumLayer pEnumLayer;
                ILayer     pLayer;
                pEnumLayer = pMap.get_Layers(null, true);
                if (pEnumLayer == null)
                {
                    return;
                }
                pEnumLayer.Reset();
                double dCurrScale = m_mapControl.MapScale;
                for (pLayer = pEnumLayer.Next(); pLayer != null; pLayer = pEnumLayer.Next())
                {
                    if (pLayer.Visible)
                    {
                        if (pLayer is IGroupLayer)
                        {
                            continue;
                        }
                        if (pLayer.MinimumScale != 0 && dCurrScale > pLayer.MinimumScale)
                        {
                            continue;
                        }
                        if (pLayer.MaximumScale != 0 && dCurrScale < pLayer.MaximumScale)
                        {
                            continue;
                        }
                        pGroupLayer.Add(pLayer);
                    }
                }

                IPoint pPoint = new ESRI.ArcGIS.Geometry.Point();
                pPoint.X = mapX; pPoint.Y = mapY;
                IIdentifyObj        pIdObj;
                IIdentify           pIdentify = pGroupLayer as IIdentify;
                IArray              pIDArray;
                IFeatureIdentifyObj pFeatIdObj;

                IEnvelope pEnv             = pPoint.Envelope;
                IDisplayTransformation pDT = m_mapControl.ActiveView.ScreenDisplay.DisplayTransformation;
                pEnv.Expand(pDT.VisibleBounds.Width / 200, pDT.VisibleBounds.Height / 200, false);

                pIDArray = pIdentify.Identify(pEnv);

                if (pIDArray == null || pIDArray.Count == 0)
                {
                    return;
                }

                pFeatIdObj = pIDArray.get_Element(0) as IFeatureIdentifyObj;
                pIdObj     = pFeatIdObj as IIdentifyObj;

                IRowIdentifyObject pRowIdentifyObj = pFeatIdObj as IRowIdentifyObject;
                IFeature           pFeature        = pRowIdentifyObj.Row as IFeature;
                if (pFeature != null && pFeature.Shape != null && !pFeature.Shape.IsEmpty)
                {
                    //axMapControl1.FlashShape(pFeature.Shape);
                    axMapControl1.Map.SelectFeature(pIdObj.Layer, pFeature);
                    FlashFeature(axMapControl1, pFeature.Shape);
                }

                //  pIdObj.Flash(m_mapControl.ActiveView.ScreenDisplay);//The Flash method is not supported with ArcGIS Engine, use the IHookActions.DoActions() method with the esriHookActionsFlash for this functionality.
                ILayer pIdentiyLayer = pIdObj.Layer;

                DataTable  pTable      = new DataTable();
                DataColumn pDataColumn = pTable.Columns.Add();
                pDataColumn.ColumnName = "列名";
                pDataColumn            = pTable.Columns.Add();
                pDataColumn.ColumnName = "值";

                DataRow pFirestDataRow = pTable.Rows.Add();
                pFirestDataRow[0] = "所在层";
                pFirestDataRow[1] = pIdentiyLayer.Name;

                if (pIdentiyLayer is IFeatureLayer)
                {
                    IRowIdentifyObject pRowObj = pIdObj as IRowIdentifyObject;
                    //   IRow pRow = pRowObj.Row;

                    IFeature pRow    = pRowObj.Row as IFeature;
                    IFields  pFields = pRow.Fields;

                    for (int i = 0; i < pFields.FieldCount; i++)
                    {
                        IField  pField   = pFields.get_Field(i);
                        DataRow pDataRow = null;

                        /*
                         * switch (pField.Type)
                         * {
                         *  case esriFieldType.esriFieldTypeOID:
                         *      pDataRow = pTable.Rows.Add();
                         *      pDataRow[0] = pField.Name;
                         *      pDataRow[1] = pRow.OID.ToString();
                         *      break;
                         *  case esriFieldType.esriFieldTypeGeometry:
                         *      //pDataRow[0] = "Geometry";
                         *      //pDataRow[1] = QueryShapeType(pField.GeometryDef.GeometryType);;
                         *      break;
                         *  default:
                         *      pDataRow = pTable.Rows.Add();
                         *      pDataRow[0] = pField.Name;
                         *      pDataRow[1] = pRow.get_Value(i).ToString();
                         *      break;
                         * }
                         * * */

                        //////////////////////////////////////////////////
                        string sValue   = pRow.get_Value(i).ToString();
                        string strFName = pField.AliasName.ToUpper();
                        string strUName = strFName.ToUpper();
                        if (strUName == "SHAPE" || strUName == "LENGTH" || strUName == "OBJECTID" || strUName == "ID" || strUName == "FNODE_" || strUName == "TNODE_" || strUName == "LPOLY_" || strUName == "RPOLY_" || strUName == "SDXL_" || strUName == "SDXL_ID" || strUName == "OBJECTID_1" || strUName == "FID")
                        {
                            continue;
                        }
                        else if (strUName == "SHAPE.LEN" || strUName == "SHAPE_LENG")
                        {
                            strFName = "几何长度";
                        }
                        else if (strUName == "SHAPE_AREA" || strUName == "SHAPE.AREA")
                        {
                            strFName = "多边形面积";
                        }
                        else if (strUName == "HEIGHT")
                        {
                            strFName = "高程";
                        }
                        else if (strUName == "NAME")
                        {
                            strFName = "名称";
                        }
                        else if (strUName == "TYPE")
                        {
                            strFName = "类型";
                        }
                        else if (strUName == "SUBTYPE")
                        {
                            strFName = "子类型";
                        }

                        if (strUName == "LENGTH" || strUName == "SHAPE.LEN")
                        {
                            IUnitConverter myUnit = new UnitConverterClass();
                            sValue = Math.Round(myUnit.ConvertUnits((double)pRow.get_Value(i), esriUnits.esriMeters, esriUnits.esriKilometers), 2).ToString();
                            sValue = sValue.ToString() + "千米";
                        }
                        if (strUName == "SHAPE_AREA" || strUName == "SHAPE.AREA")
                        {
                            IGeometry pGeo = pRow.ShapeCopy;
                            pGeo.Project(axMapControl1.Map.SpatialReference);
                            IPolygon pPolygon = (IPolygon)pGeo;
                            IArea    pArea    = (IArea)pPolygon;
                            double   strValue = pArea.Area * 0.000001;
                            //// double strValue = Math.Abs((double)pFeature.get_Value(j)) * 10585;
                            strValue = Math.Round(strValue, 2);
                            sValue   = strValue.ToString() + "平方千米";
                        }
                        esriFieldType tFieldTypy = pField.Type;
                        if (tFieldTypy == esriFieldType.esriFieldTypeGeometry)
                        {
                            sValue = pField.GeometryDef.GeometryType.ToString();
                            sValue = sValue.Substring(12, sValue.Length - 12);
                        }

                        pDataRow    = pTable.Rows.Add();
                        pDataRow[0] = strFName;
                        pDataRow[1] = sValue;

                        //////////////////////////////////////////////////
                    }
                }
                else if (pIdentiyLayer is ITinLayer)
                {
                    ITinLayer   pTinLayer   = (ITinLayer)pIdentiyLayer;
                    ITinSurface pTinSurface = (ITinSurface)pTinLayer.Dataset;
                    if (pTinSurface == null)
                    {
                        return;
                    }
                    ITinSurfaceElement pTinSurfaceElement = pTinSurface.GetSurfaceElement(pPoint);

                    if (pTinSurfaceElement == null)
                    {
                        return;
                    }
                    IFields pFields  = pTinLayer.Dataset.Fields;
                    DataRow pDataRow = null;

                    pDataRow    = pTable.Rows.Add();
                    pDataRow[0] = "高度";
                    pDataRow[1] = pTinSurfaceElement.Elevation.ToString();

                    pDataRow    = pTable.Rows.Add();
                    pDataRow[0] = "坡度";
                    pDataRow[1] = pTinSurfaceElement.SlopeDegrees.ToString();

                    pDataRow    = pTable.Rows.Add();
                    pDataRow[0] = "方向";
                    pDataRow[1] = pTinSurfaceElement.AspectDegrees.ToString();
                }

                if (pIdentiyLayer is IRasterLayer)
                {
                    MessageBox.Show("aa");
                }
                //ShowIndetify(pTable);
                //m_pMainform.ShowIndetify(pTable);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
        }
        private void DrawXlz(List <CollapsePillarsPoint> lstCollapsePillarsEntKeyPts, string sCollapseId)
        {
            ILayer mPCurrentLayer = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap,
                                                                  LayerNames.LAYER_ALIAS_MR_XianLuoZhu1);
            var pFeatureLayer = mPCurrentLayer as IFeatureLayer;
            INewBezierCurveFeedback pBezier = new NewBezierCurveFeedbackClass();
            IPoint    pt;
            IPolyline polyline = new PolylineClass();

            for (int i = 0; i < lstCollapsePillarsEntKeyPts.Count; i++)
            {
                pt = new PointClass();
                var mZAware = (IZAware)pt;
                mZAware.ZAware = true;

                pt.X = lstCollapsePillarsEntKeyPts[i].CoordinateX;
                pt.Y = lstCollapsePillarsEntKeyPts[i].CoordinateY;
                pt.Z = lstCollapsePillarsEntKeyPts[i].CoordinateZ;
                if (i == 0)
                {
                    pBezier.Start(pt);
                }
                else if (i == lstCollapsePillarsEntKeyPts.Count - 1)
                {
                    pBezier.AddPoint(pt);
                    pt = new PointClass();
                    var zZAware = (IZAware)pt;
                    zZAware.ZAware = true;
                    pt.X           = lstCollapsePillarsEntKeyPts[0].CoordinateX;
                    pt.Y           = lstCollapsePillarsEntKeyPts[0].CoordinateY;
                    pt.Z           = lstCollapsePillarsEntKeyPts[0].CoordinateZ;
                    pBezier.AddPoint(pt);
                    polyline = pBezier.Stop();
                }
                else
                {
                    pBezier.AddPoint(pt);
                }
            }
            //polyline = (IPolyline)geo;
            var pSegmentCollection = polyline as ISegmentCollection;

            if (pSegmentCollection != null)
            {
                for (int i = 0; i < pSegmentCollection.SegmentCount; i++)
                {
                    pt = new PointClass();
                    var mZAware = (IZAware)pt;
                    mZAware.ZAware = true;

                    pt.X = lstCollapsePillarsEntKeyPts[i].CoordinateX;
                    pt.Y = lstCollapsePillarsEntKeyPts[i].CoordinateY;
                    pt.Z = lstCollapsePillarsEntKeyPts[i].CoordinateZ;


                    IPoint pt1 = new PointClass();
                    mZAware        = (IZAware)pt1;
                    mZAware.ZAware = true;
                    if (i == pSegmentCollection.SegmentCount - 1)
                    {
                        pt1.X = lstCollapsePillarsEntKeyPts[0].CoordinateX;
                        pt1.Y = lstCollapsePillarsEntKeyPts[0].CoordinateY;
                        pt1.Z = lstCollapsePillarsEntKeyPts[0].CoordinateZ;

                        pSegmentCollection.Segment[i].FromPoint = pt;
                        pSegmentCollection.Segment[i].ToPoint   = pt1;
                    }
                    else
                    {
                        pt1.X = lstCollapsePillarsEntKeyPts[i + 1].CoordinateX;
                        pt1.Y = lstCollapsePillarsEntKeyPts[i + 1].CoordinateY;
                        pt1.Z = lstCollapsePillarsEntKeyPts[i + 1].CoordinateZ;

                        pSegmentCollection.Segment[i].FromPoint = pt;
                        pSegmentCollection.Segment[i].ToPoint   = pt1;
                    }
                }
            }
            polyline = pSegmentCollection as IPolyline;
            //polyline = DataEditCommon.PDFX(polyline, "Bezier");

            IPolygon pPolygon = DataEditCommon.PolylineToPolygon(polyline);
            var      list     = new List <ziduan>
            {
                new ziduan("COLLAPSE_PILLAR_NAME", lstCollapsePillarsEntKeyPts.First().CollapsePillars.CollapsePillarsName),
                new ziduan("BID", sCollapseId),
                radioBtnX.Checked ? new ziduan("XTYPE", "0") : new ziduan("XTYPE", "1")
            };
            IFeature pFeature = DataEditCommon.CreateNewFeature(pFeatureLayer, pPolygon, list);

            if (pFeature != null)
            {
                MyMapHelp.Jump(pFeature.Shape);
                DataEditCommon.g_pMyMapCtrl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewBackground, null, null);
            }

            #region 暂时无用

            //string sTempFolderPath = System.Windows.Forms.Application.StartupPath + "\\TempFolder";

            /////1.将关键点坐标存储到临时文件中
            //string sPtsCoordinateTxtPath = sTempFolderPath + "\\PtsCoordinate.txt";
            //bool bIsWrite = WritePtsInfo2Txt(lstCollapsePillarsEntKeyPts, sPtsCoordinateTxtPath);
            //if (!bIsWrite) return;

            /////2.读取点坐标文件拟合生成陷落柱,仿照等值线
            /////步骤:点文件生成点要素层→转为Raster→提取等值线
            //Geoprocessor GP = new Geoprocessor();
            //string featureOut = sTempFolderPath + "\\KeyPts.shp";
            //DrawContours.ConvertASCIIDescretePoint2FeatureClass(GP, sPtsCoordinateTxtPath, featureOut);//点文件生成点要素层

            //string sRasterOut = sTempFolderPath + "\\Raster";
            //DrawContours.ConvertFeatureCls2Raster(GP, featureOut, sRasterOut);//要素层→Raster

            //string sR2Contour = sTempFolderPath + "\\Contour.shp";
            //double douElevation = 0.5;//等高距0.5
            //DrawContours.SplineRasterToContour(GP, sRasterOut, sR2Contour, douElevation);//提取等值线(即为拟合的陷落柱)

            /////3.复制生成的等值线(即为拟合的陷落柱)要素到陷落柱图层
            /////3.1 获得源图层
            //IFeatureLayer sourceFeaLayer = new FeatureLayerClass();
            //string sourcefeatureClassName = "Contour.shp";
            //IFeatureClass featureClass =PointsFit2Polyline.GetFeatureClassFromShapefileOnDisk(sTempFolderPath, sourcefeatureClassName);//获得等值线(即为拟合的陷落柱)图层

            //if (featureClass == null) return;
            //sourceFeaLayer.FeatureClass = featureClass;


            /////3.2 获得当前编辑图层(目标图层)
            //DrawSpecialCommon drawspecial = new DrawSpecialCommon();
            //string sLayerAliasName = LibCommon.LibLayerNames.DEFALUT_COLLAPSE_PILLAR;//“默认_陷落柱_1”图层
            //IFeatureLayer featureLayer = drawspecial.GetFeatureLayerByName(sLayerAliasName);
            //if (featureLayer == null)
            //{
            //    MessageBox.Show("未找到" + sLayerAliasName + "图层,无法绘制陷落柱图元。");
            //    return;
            //}

            /////3.3 复制要素
            //PointsFit2Polyline.CopyFeature(sourceFeaLayer, featureLayer, sCollapseID);

            #endregion
        }
Example #60
0
 /// <summary>
 /// Triangulates a polygon.
 /// </summary>
 public static IMesh Triangulate(this IPolygon polygon)
 {
     return((new GenericMesher()).Triangulate(polygon, null, null));
 }