private void SetPINValue()
    {
      //The Theory.
      //Select polygons that intersect the sketch.
      //Construct one polyline from the boundaries and intersect with sketch.
      //Sort resulting intersection locations (multipoint) by distance of the intersect
      // from the start of the sketch and create new ordered multipoint.
      //Loop through new ordered multipoint, select underlying parcel and calc pin.

      IFeatureLayer featLayer = m_editLayers.CurrentLayer;
      m_curve = m_edSketch.Geometry as IPolyline;

      //Search parcel polys by graphic to get feature cursor
      ISpatialFilter spatialFilter = new SpatialFilter();
      spatialFilter.Geometry = m_curve;
      spatialFilter.GeometryField = m_editLayers.CurrentLayer.FeatureClass.ShapeFieldName;
      spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelCrosses;

      IFeatureCursor featCursor = featLayer.Search(spatialFilter,true);
      IFeature feature = featCursor.NextFeature();

      //If we have no intersects then exit
      if (feature == null)
        return;
  
      //Make a GeomBag of the polygons boundaries (polylines)
      IGeometryCollection geomBag = new GeometryBagClass();
      object missing = Type.Missing;
      while (feature != null)
      {
        ITopologicalOperator poly = feature.Shape as ITopologicalOperator;
        geomBag.AddGeometry(poly.Boundary,ref missing,ref missing);
        feature = featCursor.NextFeature();
      }

      //Make one polyline from the boundaries
      IPolyline polyLineU = new PolylineClass();
      ITopologicalOperator topoOp = polyLineU as ITopologicalOperator;
      topoOp.ConstructUnion(geomBag as IEnumGeometry);

      //Get the intersections of the boundaries and the curve
      IPointCollection pointCol = topoOp.Intersect(m_curve, esriGeometryDimension.esriGeometry0Dimension) as IPointCollection;

      //The point collection is not ordered by distance along the curve so
      //need to create a new collection with this info

      int[] pointOrder = new int[pointCol.PointCount];
      double dac = 0, dfc = 0;
      bool bRS = false;

      for (int i = 0; i < pointCol.PointCount; i++)
      {
        IPoint queryPoint = new PointClass();
        pointCol.QueryPoint(i, queryPoint);
        m_curve.QueryPointAndDistance(esriSegmentExtension.esriNoExtension, queryPoint, false, null,ref dac,ref dfc,ref bRS);
        pointOrder[i] = (int)dac;
      }

      //use built in bubble sort
      System.Array.Sort(pointOrder);

      //Loop through the sorted array and calc midpoint between parcel boundaries
      IPointCollection midPoints = new MultipointClass();

      for (int i = 0; i < pointOrder.Length -1; i++)
      {
        //Get the midpoint distance
        double midPointDist = (pointOrder[i] + pointOrder[i + 1]) / 2;
        
        //create a point at the distance and store in point collection
        IPoint queryPoint = new PointClass();
        m_curve.QueryPoint(esriSegmentExtension.esriNoExtension, midPointDist, false, queryPoint);
        midPoints.AddPoint(queryPoint,ref missing,ref missing);
      }

      //If ends of sketch are included then add them as points
      if (chkEnds.Checked)
      {
        object before = 0 as object;
        midPoints.AddPoint(m_curve.FromPoint, ref before, ref missing);
        midPoints.AddPoint(m_curve.ToPoint, ref missing, ref missing);
      }

      m_editor.StartOperation();

      //Loop through calculated midpoints, select polygon and calc pin
      for (int i = 0; i < midPoints.PointCount; i++)
      {
        IPoint midPoint = midPoints.get_Point(i);
        spatialFilter = new SpatialFilter();
        spatialFilter.Geometry = midPoint;
        spatialFilter.GeometryField = m_editLayers.CurrentLayer.FeatureClass.ShapeFieldName;
        spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelWithin;

        featCursor = featLayer.Search(spatialFilter, false);
        while ((feature = featCursor.NextFeature()) != null)
        {
          feature.set_Value(feature.Fields.FindField(cmbPINField.Text), m_lotNum);
          feature.Store();
          m_lotNum += int.Parse(txtlotinc.Text);
        }
      }
      m_editor.StopOperation("ViperPIN");
      txtlot.Text = m_lotNum.ToString();
    }
Example #2
0
        /// <summary>
        /// 计算面积
        /// </summary>
        /// <param name="CurPoint"></param>
        /// <returns></returns>
        private double CaculateArea(IPoint CurPoint)
        {
            IPointCollection tempCollection = new MultipointClass();

            object missing = Type.Missing;

            for (int i = 0; i < m_ptCollection.PointCount; i++)
            {
                IPoint dPoint = m_ptCollection.get_Point(i);
                tempCollection.AddPoint(dPoint, ref missing, ref missing);
            }

            tempCollection.AddPoint(CurPoint, ref missing, ref missing);
            tempCollection.AddPoint(tempCollection.get_Point(0), ref missing, ref missing);
            int Count = tempCollection.PointCount;

            double x1, x2, y1, y2;
            double tempArea = 0.0;

            for (int i = 0; i < Count - 1; i++)
            {
                x1        = Convert.ToDouble(tempCollection.get_Point(i).X);
                y1        = Convert.ToDouble(tempCollection.get_Point(i).Y);
                x2        = Convert.ToDouble(tempCollection.get_Point(i + 1).X);
                y2        = Convert.ToDouble(tempCollection.get_Point(i + 1).Y);
                tempArea += (x1 * y2 - x2 * y1);
            }

            tempArea = Math.Abs(tempArea) / 2;
            return(tempArea);
        }
        public override void OnMouseDown(int Button, int Shift, int X, int Y)
        {
            // TODO:  Add RouteQuery.OnMouseDown implementation
            if (networkanalasia == true)
            {
                IPointCollection m_ipPoints;//输入点集合
                IPoint           ipNew;
                m_ipPoints = new MultipointClass();
                ipNew      = axMapControl.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
                object o = Type.Missing;
                m_ipPoints.AddPoint(ipNew, ref o, ref o);
                CreateFeature(inputFClass, m_ipPoints);//获取用鼠标点击最近点
                //把最近的点显示出来
                IElement     element;
                ITextElement textelement = new TextElementClass();
                element = textelement as IElement;
                ITextSymbol textSymbol = new ESRI.ArcGIS.Display.TextSymbol();

                textelement.Symbol = textSymbol;
                clickedcount++;
                textelement.Text = clickedcount.ToString();
                element.Geometry = m_ipActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
                PGC.AddElement(element, 0);

                m_ipActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
            }
        }
        public IPointCollection4 ToPointCollection(IGeometry geometry, out int nrPoints)
        {
            IPointCollection4 result = null;

            nrPoints = 0;

            if (geometry != null)
            {
                result = geometry as IPointCollection4;
                TypeOfLayer typeOfLayer = GetTypeOfLayer(geometry);

                if ((!geometry.IsEmpty) && (typeOfLayer == TypeOfLayer.Point) && (result == null) && IsPointMeasurement)
                {
                    var pointc = geometry as IPoint;
                    result = new MultipointClass();
                    result.AddPoint(pointc);
                }

                if (result != null)
                {
                    nrPoints = result.PointCount;

                    if ((nrPoints >= 2) && (typeOfLayer == TypeOfLayer.Polygon))
                    {
                        IPoint point1 = result.Point[0];
                        IPoint point2 = result.Point[nrPoints - 1];
                        nrPoints = (point1.Compare(point2) == 0) ? (nrPoints - 1) : nrPoints;
                    }
                }
            }

            return(result);
        }
Example #5
0
        //节点捕捉
        private static void GetNodeCollection(List <IFeature> listFeats, IFeatureClass pFeatureClass, IProximityOperator pProximity, double dSearchDist)
        {
            IPointCollection pPntColTemp = new MultipointClass();

            for (int i = 0; i < listFeats.Count; i++)
            {
                IFeature pFeature = listFeats[i];
                //判断该Feature图层
                if (pFeature.Class.ObjectClassID != pFeatureClass.ObjectClassID)
                {
                    continue;
                }

                double dScreenSearchDist = pProximity.ReturnDistance(pFeature.Shape);
                if (dScreenSearchDist < 1.5 * dSearchDist)
                {
                    if (pFeature.Shape.GeometryType == esriGeometryType.esriGeometryPoint)
                    {
                        IPoint pPoint = pFeature.Shape as IPoint;
                        object befor  = Type.Missing;
                        object after  = Type.Missing;
                        m_PointCollection.AddPoint(pPoint, ref befor, ref after);
                        pPntColTemp.AddPoint(pPoint, ref befor, ref after);
                    }
                    else
                    {
                        IPointCollection pTempPtcln = pFeature.Shape as IPointCollection;
                        m_PointCollection.AddPointCollection(pTempPtcln);
                        pPntColTemp.AddPointCollection(pTempPtcln);
                    }
                }
            }

            m_dicPointCollection.Add(pPntColTemp, "Node");
        }
Example #6
0
        public static void ReadPolugon(this ImportSentinelData importProduct)
        {
            if (string.IsNullOrWhiteSpace(importProduct.Footprint))
            {
                return;
            }

            string text = importProduct.Footprint;

            //"<gml:Polygon srsName=\"http://www.opengis.net/gml/srs/epsg.xml#4326\" xmlns:gml=\"http://www.opengis.net/gml\"><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>45.308281,24.306789 45.711151,21.006590 47.207355,21.359417 46.803715,24.750584 45.308281,24.306789</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon>";


            var doc  = XDocument.Parse(text);
            var elem = doc.Descendants(XName.Get("coordinates", "http://www.opengis.net/gml")).Select(node =>
            {
                var pointCollection = new MultipointClass();
                node.Value.Split(' ').Select(p =>
                {
                    var coords = p.Split(','); return(new Point {
                        X = coords[1].ParceToDouble(), Y = coords[0].ParceToDouble(), SpatialReference = EsriTools.Wgs84Spatialreference
                    });
                }).ToList().ForEach(p => pointCollection.AddPoint(p));

                return(EsriTools.GetPolygonByPointCollection(pointCollection));
            });

            importProduct.FootprintPoly = elem.FirstOrDefault();
        }
        private IFeature Convert_Point2MultiPoint_Class(IFeatureClass PointFeatureClass)
        {
            IWorkspaceFactory contourWSF   = new ShapefileWorkspaceFactoryClass();
            IFeatureWorkspace contourFWS   = (IFeatureWorkspace)contourWSF.OpenFromFile(WorkSpaceName, 0);
            IFields           pFields      = CreateShapeFields(esriGeometryType.esriGeometryMultipoint);
            string            filename     = PointFeatureClass.AliasName + "_muilti";
            string            filename_shp = WorkSpaceName + @"/" + filename + ".shp";

            if (System.IO.File.Exists(filename_shp))
            {
                System.IO.File.Delete(filename_shp);
                System.IO.File.Delete(System.IO.Path.ChangeExtension(filename_shp, ".dbf"));
                System.IO.File.Delete(System.IO.Path.ChangeExtension(filename_shp, ".shx"));
            }
            contourFWS.CreateFeatureClass(filename, pFields, null, null, esriFeatureType.esriFTSimple, "Shape", null);
            IFeatureClass    MultiFeatureClass = contourFWS.OpenFeatureClass(filename);
            IPointCollection pPointCollection  = new MultipointClass();

            for (int i = 0; i < PointFeatureClass.FeatureCount(null); i++)
            {
                IFeature pFeature = PointFeatureClass.GetFeature(i);
                IPoint   pPoint   = pFeature.Shape as IPoint;
                pPointCollection.AddPoint(pPoint);
            }
            IFeature MultiFeature = MultiFeatureClass.CreateFeature();

            MultiFeature.Shape = pPointCollection as IGeometry;
            MultiFeature.Store();
            return(MultiFeature);
        }
Example #8
0
        static void createWkbMultiLineString(byte[] wkb, ref int startIndex, BitConversion bitConversion, out IGeometry geometry)
        {
            geometry = new PolylineClass();
            IPointCollection mp = (IPointCollection)geometry;

            // Get the number of line strings.
            UInt32 lineStringCnt;

            getWkbUInt32(wkb, ref startIndex, bitConversion, out lineStringCnt);

            UInt32 pointCnt;
            double x, y;
            object missing = Type.Missing;

            // Loop through each LineString.
            for (int i = 0; i < lineStringCnt; i++)
            {
                startIndex += 5;  // Jump past useless header stuff.
                getWkbUInt32(wkb, ref startIndex, bitConversion, out pointCnt);

                IPointCollection tempPc = new MultipointClass();
                // Loop through each point.
                for (int j = 0; j < pointCnt; j++)
                {
                    getWkbDouble(wkb, ref startIndex, bitConversion, out x);
                    getWkbDouble(wkb, ref startIndex, bitConversion, out y);
                    tempPc.AddPoint(createAoPoint(x, y), ref missing, ref missing);
                }
                mp.AddPointCollection(tempPc);
            }
        }
        public void AddZToSketch(IEditSketch3 sketch)
        {
            var    editor  = ArcUtils.Editor;
            var    editorZ = editor as IEditorZ;
            IPoint point   = sketch.LastPoint;

            if ((editorZ != null) && (point != null) && sketch.ZAware)
            {
                double z = GetHeight(point.X, point.Y);
                editorZ.UseZOffset = true;
                editorZ.ZOffset    = z;

                IGeometry         geometry = sketch.Geometry;
                var               ptColl   = geometry as IPointCollection4;
                ISketchOperation2 sketchOp = new SketchOperationClass();
                sketchOp.Start(editor);
                IPoint pointc = null;

                if ((!geometry.IsEmpty) && (geometry is IPoint) && (ptColl == null))
                {
                    pointc = geometry as IPoint;
                    ptColl = new MultipointClass();
                    ptColl.AddPoint(pointc);
                }

                if (ptColl != null)
                {
                    int nrPoints = ptColl.PointCount;

                    for (int i = 0; i < nrPoints; i++)
                    {
                        IPoint pointC = ptColl.Point[i];
                        // ReSharper disable CompareOfFloatsByEqualityOperator

                        if (pointC.Z == 0)
                        {
                            IPoint newPoint = new PointClass {
                                X = pointC.X, Y = pointC.Y, Z = z
                            };
                            ptColl.UpdatePoint(i, newPoint);
                        }

                        // ReSharper restore CompareOfFloatsByEqualityOperator
                    }
                }

                sketch.Geometry = pointc ?? (ptColl as IGeometry);
                geometry        = sketch.Geometry;

                if (geometry != null)
                {
                    sketchOp.Finish(geometry.Envelope, esriSketchOperationType.esriSketchOperationGeneral, geometry);
                }
            }
        }
        private IPointCollection Convert_Point2MultiPoint(IFeatureClass PointFeatureClass)
        {
            IPointCollection pPointCollection = new MultipointClass();

            for (int i = 0; i < PointFeatureClass.FeatureCount(null); i++)
            {
                IFeature pFeature = PointFeatureClass.GetFeature(i);
                IPoint   pPoint   = pFeature.Shape as IPoint;
                pPointCollection.AddPoint(pPoint);
            }
            return(pPointCollection);
        }
Example #11
0
        private int ReportPointErrors(
            [NotNull] IDictionary <int, List <int> > pointIndexesById,
            int maxPointsId,
            [NotNull] Rings rings,
            [NotNull] IRow row)
        {
            object missing = Type.Missing;

            IPointCollection points = new MultipointClass();

            GeometryUtils.EnsureSpatialReference((IGeometry)points,
                                                 rings.SpatialReference);

            foreach (KeyValuePair <int, List <int> > pair in pointIndexesById)
            {
                int id = pair.Key;
                if (id == maxPointsId)
                {
                    continue;
                }

                List <int> pointIndexes = pair.Value;

                foreach (int pointIndex in pointIndexes)
                {
                    IPoint point = rings.get_Point(pointIndex);
                    points.AddPoint(point, ref missing, ref missing);
                }
            }

            string description;

            if (rings.RingsCount > 1)
            {
                description = string.Format(
                    "The point ids of these points differ from the most frequent point id {0} " +
                    "({1} occurrences) in the rings (outer ring = {2}. patch in multipatch)",
                    maxPointsId, pointIndexesById[maxPointsId].Count,
                    rings.FirstPatchIndex + 1);
            }
            else
            {
                description = string.Format(
                    "The point ids of these points differ from the most frequent point id {0} " +
                    "({1} occurrences) in the ring ({2}. patch in Multipatch)",
                    maxPointsId, pointIndexesById[maxPointsId].Count,
                    rings.FirstPatchIndex + 1);
            }

            return(ReportError(description, (IGeometry)points, Codes[Code.DifferentIdInRing],
                               TestUtils.GetShapeFieldName(row), row));
        }
        public IGeometry GetMultipointGeometry()
        {
            const double MultipointPointCount = 25;

            IPointCollection pPointCollection = new MultipointClass();

            for (int i = 0; i < MultipointPointCount; i++)
            {
                pPointCollection.AddPoint(GetPoint(), ref pMissing, ref pMissing);
            }

            return pPointCollection as IGeometry;
        }
        public IGeometry GetMultipointGeometry()
        {
            const double MultipointPointCount = 25;

            IPointCollection pPointCollection = new MultipointClass();

            for (int i = 0; i < MultipointPointCount; i++)
            {
                pPointCollection.AddPoint(GetPoint(), ref pMissing, ref pMissing);
            }

            return(pPointCollection as IGeometry);
        }
Example #14
0
        /// <summary>
        /// 获得一个Geometry的所有顶点
        /// </summary>
        /// <param name="sourceGeom"></param>
        /// <returns></returns>
        public static IMultipoint GetVertices(IGeometry pGeometry)
        {
            if (pGeometry == null)
            {
                return(null);
            }

            IPointCollection pPointCollection = new MultipointClass();

            object obj = null;

            if (pGeometry is IPoint)
            {
                pPointCollection.AddPoint(pGeometry as IPoint, ref obj, ref obj);
                return(pPointCollection as IMultipoint);
            }
            else if (pGeometry is ISegment)
            {
                ISegment pSegment = pGeometry as ISegment;
                pPointCollection.AddPoint(pSegment.FromPoint, ref obj, ref obj);
                pPointCollection.AddPoint(pSegment.ToPoint, ref obj, ref obj);
            }
            else if (pGeometry is IEnvelope)
            {
                IEnvelope pEnvelope = pGeometry as IEnvelope;
                pPointCollection.AddPoint(pEnvelope.UpperLeft, ref obj, ref obj);
                pPointCollection.AddPoint(pEnvelope.UpperRight, ref obj, ref obj);
                pPointCollection.AddPoint(pEnvelope.LowerLeft, ref obj, ref obj);
                pPointCollection.AddPoint(pEnvelope.LowerRight, ref obj, ref obj);
            }
            else if (pGeometry is IGeometryCollection)
            {
                IGeometryCollection pGeometryCollection = pGeometry as IGeometryCollection;
                for (int i = 0; i < pGeometryCollection.GeometryCount; i++)
                {
                    IGeometry        pSubGeo             = pGeometryCollection.get_Geometry(i);
                    IPointCollection pSubPointCollection = GetVertices(pSubGeo) as IPointCollection;
                    if (pSubPointCollection != null)
                    {
                        pPointCollection.AddPointCollection(pSubPointCollection);
                    }
                }
            }

            if (pPointCollection.PointCount == 0)
            {
                return(null);
            }
            else
            {
                return(pPointCollection as IMultipoint);
            }
        }
Example #15
0
        public IPolyline QueryTheRoue2(IPoint breakPoint, IMap pMap, IFeatureLayer featureLayer, string dbPath, ref IPoint rightPoint)
        {
            IFeature feature  = null;
            double   distance = 0;
            int      distNum  = 0;

            rightPoint = DistanceUtil.GetNearestLineInFeatureLayer(featureLayer, breakPoint, ref feature, ref distance, ref distNum);
            if (rightPoint == null)
            {
                return(null);
            }
            //获取线要素的点集合
            IPointCollection lineCollection = feature.Shape as IPointCollection;
            //将线要素的起点和终点加入路线点集合中
            IPointCollection routePointCollection = new MultipointClass();

            routePointCollection.AddPoint(lineCollection.get_Point(0));
            routePointCollection.AddPoint(lineCollection.get_Point(lineCollection.PointCount - 1));
            //查询最短路径
            IPolyline polyline = UtilityNetWorkUtil.DistanceFun(pMap, dbPath, "roads", 1, routePointCollection, "length", 50);

            return(polyline);
        }
Example #16
0
        private static IGeometry GetErrorGeometry([NotNull] LineListPolygon poly)
        {
            object missing = Type.Missing;

            IPointCollection multiPoint = new MultipointClass();

            foreach (IRow pointRow in poly.Centroids)
            {
                multiPoint.AddPoint(((IFeature)pointRow).Shape as Point, ref missing,
                                    ref missing);
            }

            return((IGeometry)multiPoint);
        }
Example #17
0
        private void updatePointToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IMultipoint multipoint;
            object      missing = Type.Missing;
            IPoint      point1  = new PointClass();

            point1.PutCoords(10, 10);
            IPoint point2 = new PointClass();

            point2.PutCoords(20, 20);
            IPointCollection pointCollection = new MultipointClass();

            pointCollection.AddPoint(point1, ref missing, ref missing);
            pointCollection.AddPoint(point2, ref missing, ref missing);
            point1 = new PointClass();
            point1.PutCoords(40, 10);
            pointCollection.UpdatePoint(1, point1);
            multipoint = pointCollection as IMultipoint;
            addFeature("multipoint", multipoint as IGeometry);
            System.Windows.Forms.MessageBox.Show("X = " + pointCollection.get_Point(1).X +
                                                 ", Y = " + pointCollection.get_Point(1).Y);
            this.axMapControl1.Extent = multipoint.Envelope;
            this.axMapControl1.Refresh();
        }
Example #18
0
        private void btnDeleteLink_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection rowCollection = this.dataGridViewX1.SelectedRows;
            int nCount    = rowCollection.Count;
            int nOriCount = m_OriginPoints.PointCount;

            IPointCollection tmpPointCollectionOri = new MultipointClass();
            IPointCollection tmpPointCollectionDst = new MultipointClass();

            for (int i = 0; i < nOriCount; i++)
            {
                bool bFlag = false;
                for (int j = 0; j < nCount; j++)
                {
                    if (i == rowCollection[j].Index)
                    {
                        bFlag = true;
                        break;
                    }
                }

                if (bFlag == false)
                {
                    tmpPointCollectionOri.AddPoint(m_OriginPoints.get_Point(i));
                    tmpPointCollectionDst.AddPoint(m_TargetPoints.get_Point(i));
                }
            }

            m_OriginPoints.RemovePoints(0, m_OriginPoints.PointCount);
            m_TargetPoints.RemovePoints(0, m_TargetPoints.PointCount);
            for (int i = 0; i < tmpPointCollectionDst.PointCount; i++)
            {
                m_OriginPoints.AddPoint(tmpPointCollectionOri.get_Point(i));
                m_TargetPoints.AddPoint(tmpPointCollectionDst.get_Point(i));
            }

            RefreshDataTable();

            //m_pMapCtr.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
            //m_pMapCtr.RefreshLayer();
            //if (refreshLayer != null)
            //{
            //    refreshLayer();
            //}
        }
Example #19
0
        //中点捕捉
        private static void GetMidPntCollection(List <IFeature> listFeats, IFeatureClass pFeatureClass, IProximityOperator pProximity, double dSearchDist)
        {
            IPointCollection pPntColTemp = new MultipointClass();

            for (int i = 0; i < listFeats.Count; i++)
            {
                IFeature pFeature = listFeats[i];
                //判断该Feature图层
                if (pFeature.Class.ObjectClassID != pFeatureClass.ObjectClassID)
                {
                    continue;
                }

                if (pFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolyline || pFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolygon)
                {
                    double dScreenSearchDist = pProximity.ReturnDistance(pFeature.Shape);
                    if (dScreenSearchDist < 1.5 * dSearchDist)
                    {
                        IGeometryCollection pGeoCollection = pFeature.Shape as IGeometryCollection;
                        for (int j = 0; j < pGeoCollection.GeometryCount; j++)
                        {
                            IGeometry          pGeom    = pGeoCollection.get_Geometry(j);
                            ISegmentCollection pSegColl = pGeom as ISegmentCollection;

                            for (int k = 0; k < pSegColl.SegmentCount; k++)
                            {
                                ISegment pSeg      = pSegColl.get_Segment(k);
                                IPoint   pMidPoint = new PointClass();
                                double   x         = (pSeg.FromPoint.X + pSeg.ToPoint.X) / 2;
                                double   y         = (pSeg.FromPoint.Y + pSeg.ToPoint.Y) / 2;
                                pMidPoint.PutCoords(x, y);
                                object befor = Type.Missing;
                                object after = Type.Missing;
                                m_PointCollection.AddPoint(pMidPoint, ref befor, ref after);
                                pPntColTemp.AddPoint(pMidPoint, ref befor, ref after);
                            }
                        }
                    }
                }
            }

            m_dicPointCollection.Add(pPntColTemp, "MidPnt");
        }
Example #20
0
        //确定键
        private void buttonOK_Click(object sender, EventArgs e)
        {
            double dL = 0.0, dB = 0.0, dZJ = 0.0;
            bool   bL  = double.TryParse(textBoxLong.Text, out dL);   //经度
            bool   bB  = double.TryParse(textBoxLat.Text, out dB);    //纬度
            bool   bZJ = double.TryParse(textBoxLevel.Text, out dZJ); //震级

            time = textBoxTime.Text;                                  //时间

            //开启编辑状态
            IWorkspaceFactory pWorkspaceFactory = new AccessWorkspaceFactoryClass();
            IFeatureWorkspace pFeatureWorkspace = pWorkspaceFactory.OpenFromFile(dataFile, 0) as IFeatureWorkspace;
            IWorkspaceEdit    pWorkspaceEdit    = pFeatureWorkspace as IWorkspaceEdit;

            pWorkspaceEdit.StartEditing(false);
            pWorkspaceEdit.StartEditOperation();
            //插入余震点数据
            IFeatureClass      pFeatureClassPoint = pFeatureLayerPoint.FeatureClass;
            IFeatureClassWrite fwritePoint        = pFeatureClassPoint as IFeatureClassWrite;
            IFeature           pFeaturePoint      = pFeatureClassPoint.CreateFeature();
            IPointCollection   pointCollection    = new MultipointClass();
            IPoint             pPoint             = new PointClass();
            IGeoDataset        pGeoDataset        = pFeatureClassPoint as IGeoDataset;
            //记录空间投影信息
            ISpatialReference spatialReference = pGeoDataset.SpatialReference;

            //输入经纬度
            pPoint.PutCoords(dL, dB);
            pPoint.SpatialReference = spatialReference;
            pointCollection.AddPoint(pPoint, ref _missing, ref _missing);
            pFeaturePoint.Shape = pointCollection as IGeometry;
            //设置属性值
            pFeaturePoint.set_Value(3, dZJ);
            pFeaturePoint.set_Value(5, time + "," + textBoxLevel.Text);
            fwritePoint.WriteFeature(pFeaturePoint);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeaturePoint);

            pFeaturePoint = null;
            pWorkspaceEdit.StopEditOperation();
            pWorkspaceEdit.StopEditing(true);
            this.Hide();
            MessageBox.Show("操作成功!", "提示");
        }
Example #21
0
        //最近点捕捉
        private static void GetNearestPntCollection(List <IFeature> listFeats, IFeatureClass pFeatureClass, IPoint pPnt, double dSearchDist)
        {
            IPointCollection pPntColTemp = new MultipointClass();

            for (int i = 0; i < listFeats.Count; i++)
            {
                IFeature pFeature = listFeats[i];
                if (pFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolyline || pFeature.Shape.GeometryType == esriGeometryType.esriGeometryPolygon)
                {
                    IProximityOperator pProximity  = pFeature.Shape as IProximityOperator;
                    IPoint             pNearestPnt = pProximity.ReturnNearestPoint(pPnt, esriSegmentExtension.esriNoExtension);
                    object             befor       = Type.Missing;
                    object             after       = Type.Missing;
                    m_PointCollection.AddPoint(pNearestPnt, ref befor, ref after);
                    pPntColTemp.AddPoint(pNearestPnt, ref befor, ref after);
                }
            }

            m_dicPointCollection.Add(pPntColTemp, "NearestPnt");
        }
Example #22
0
        //从点图层中收集所有点
        public IPointCollection ReadPoint(IFeatureLayer pFeatureLayer)
        {
            IFeatureCursor pFeatureCursor = pFeatureLayer.Search(null, false);

            //获取数据库或者单个文件的第一个属性字段
            IFeature pFeature = pFeatureCursor.NextFeature();
            IField   pField   = null;

            if (pFeatureLayer.FeatureClass.Fields.FindField("FID") != -1)
            {
                pField = pFeatureLayer.FeatureClass.Fields.get_Field(pFeatureLayer.FeatureClass.Fields.FindField("FID"));
            }
            else if (pFeatureLayer.FeatureClass.Fields.FindField("OBJECTID") != -1)
            {
                pField = pFeatureLayer.FeatureClass.Fields.get_Field(pFeatureLayer.FeatureClass.Fields.FindField("OBJECTID"));
            }

            //第一个属性字段名称
            string FirstFieldName = pField.AliasName;

            IQueryFilter pQueryFilter = new QueryFilterClass();

            pQueryFilter.WhereClause = FirstFieldName + ">=0";
            int number = pFeatureLayer.FeatureClass.FeatureCount(pQueryFilter);

            IPointCollection pPointCollection = new MultipointClass();

            for (int i = 0; i < number; i++)
            {
                IGeometry pGeometry = pFeature.Shape as IGeometry;
                IPoint    pPoint    = pGeometry as IPoint;

                pPointCollection.AddPoint(pPoint);

                pFeature = pFeatureCursor.NextFeature();
            }

            return(pPointCollection);
        }
Example #23
0
        private static IMultipoint GetPointsAtMs([NotNull] IPolyline polyline,
                                                 params double[] mValues)
        {
            Assert.ArgumentNotNull(polyline, nameof(polyline));

            var result = new MultipointClass {
                SpatialReference = polyline.SpatialReference
            };

            GeometryUtils.MakeMAware(result);
            if (GeometryUtils.IsZAware(polyline))
            {
                GeometryUtils.MakeZAware(result);
            }

            var mSegmentation = (IMSegmentation3)polyline;

            object emptyRef = Type.Missing;

            foreach (double mValue in mValues)
            {
                IGeometryCollection points = mSegmentation.GetPointsAtM(mValue, 0);

                int pointCount = points.GeometryCount;

                for (var i = 0; i < pointCount; i++)
                {
                    result.AddPoint((IPoint)points.Geometry[i], ref emptyRef, ref emptyRef);
                }
            }

            // eliminate duplicates
            GeometryUtils.Simplify(result);

            return(result);
        }
 public static IPoint Snapping(IActiveView activeView, esriGeometryHitPartType geometryHitPartType, IPoint queryPoint, double searchRaius)
 {
     IPoint vetexPoint = null;
     IPoint hitPoint = new PointClass();
     IHitTest hitTest = null;
     IPointCollection pointCollection = new MultipointClass();
     IProximityOperator proximityOperator = null;
     double hitDistance = 0;
     int hitPartIndex = 0, hitSegmentIndex = 0;
     Boolean rightSide = false;
     IFeatureCache2 featureCache = new FeatureCacheClass();
     featureCache.Initialize(queryPoint, searchRaius);  //初始化缓存
     for (int i = 0; i < activeView.FocusMap.LayerCount; i++)
     {
         //只有点、线、面并且可视的图层才加入缓存
         IFeatureLayer featLayer = (IFeatureLayer)activeView.FocusMap.get_Layer(i);
         if (featLayer != null && featLayer.Visible == true &&
             (featLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolyline ||
             featLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon ||
             featLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPoint))                
         {
             featureCache.AddFeatures(featLayer.FeatureClass, null);
             for (int j = 0; j < featureCache.Count; j++)
             {
                 IFeature feature = featureCache.get_Feature(j);
                 hitTest = (IHitTest)feature.Shape;
                 //捕捉节点,另外可以设置esriGeometryHitPartType,捕捉边线点,中间点等。
                 if (hitTest.HitTest(queryPoint, searchRaius, geometryHitPartType, hitPoint, ref hitDistance, ref hitPartIndex, ref hitSegmentIndex, ref rightSide))
                 {
                     object obj = Type.Missing;
                     pointCollection.AddPoint(hitPoint, ref obj, ref obj);
                     break;
                 }
             }
         }
     }
     proximityOperator = (IProximityOperator)queryPoint;
     double minDistance = 0, distance = 0;
     for (int i = 0; i < pointCollection.PointCount; i++)
     {
         IPoint tmpPoint = pointCollection.get_Point(i);
         distance = proximityOperator.ReturnDistance(tmpPoint);
         if (i == 0)
         {
             minDistance = distance;
             vetexPoint = tmpPoint;
         }
         else
         {
             if (distance < minDistance)
             {
                 minDistance = distance;
                 vetexPoint = tmpPoint;
             }
         }
     }
     return vetexPoint;            
 }
        private KeyValuePair<IGeoDataset, IGeoDataset> computeWatershed(IPoint pour_point, IEnvelope analysisExtent)
        {
            try
            {
                //bodge the input point into its nasty shell of arcobjects junk for analysis
                IHydrologyOp pHydrologyOp = new RasterHydrologyOp() as IHydrologyOp;
                IPointCollection3 tPointCollection = new MultipointClass();
                object tPointlessMissingObject = Type.Missing;
                tPointCollection.AddPoint(pour_point, ref tPointlessMissingObject, ref tPointlessMissingObject);

                // open the accumulation and direction datasets, hardcoded
                //IGeoDataset tAccum = OpenRasterDataset(data_path, accum_name) as IGeoDataset;
                //IGeoDataset tDirection = OpenRasterDataset(data_path, dir_name) as IGeoDataset;
                //bodge the input extent into its nasty shell of arcobjects junk
                IRasterAnalysisEnvironment tRasterAnalysisEnvironment = new RasterAnalysisClass();
                if (analysisExtent != null)
                {
                    IRelationalOperator tCheckRequestedExtent = analysisExtent as IRelationalOperator;
                    if (tCheckRequestedExtent != null && tCheckRequestedExtent.Contains(pour_point))
                    {
                        // can anyone explain why these things have to be objects? Why can't there be interfaces
                        // for AnalysisExtentProvider and SnapObject that the datasets implement?
                        object tAnalysisEnvelopePointlesslyCastedToObject = (System.Object)analysisExtent;
                        object tAnotherPointlessMissingObject = Type.Missing;
                        //object tSnapObject = (System.Object)tDirection;
                        object tSnapObject = (System.Object)m_FlowDirDataset;
                        tRasterAnalysisEnvironment.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue,
                            ref tAnalysisEnvelopePointlesslyCastedToObject, ref tSnapObject);
                        tRasterAnalysisEnvironment.SetAsNewDefaultEnvironment();
                    }
                    else
                    {
                        logger.LogMessage(ServerLogger.msgType.warning, "create watershed", 8000,
                            "Input point was not within requested analysis extent. Analysis extent will be ignored (may be slow)!");
                    }
                }
                else
                {
                    logger.LogMessage(ServerLogger.msgType.warning, "create watershed", 8000,
                        "No analysis extent requested. Full extent will be used (may be slow)!");

                }
                IExtractionOp tExtractionOp = new RasterExtractionOpClass();

                // Do the work: snap the point to a snapped-pour-point grid and use it to calcualte the watershed
                //IGeoDataset tPourPointGrid = tExtractionOp.Points(tDirection, tPointCollection, true);
                IGeoDataset tPourPointGrid = tExtractionOp.Points(m_FlowDirDataset, tPointCollection, true);
                //IGeoDataset snapRaster = pHydrologyOp.SnapPourPoint(tPourPointGrid, tAccum, 100);
                IGeoDataset snapRaster = pHydrologyOp.SnapPourPoint(tPourPointGrid, m_FlowAccDataset, 100);
                // check the snapping worked..?
                // calculate the watershed!
                //IGeoDataset watershedRaster = pHydrologyOp.Watershed(tDirection, snapRaster);
                IGeoDataset watershedRaster = pHydrologyOp.Watershed(m_FlowDirDataset, snapRaster);
                //  restore previous default analysis extent if we changed it (should = whole dataset)
                if (analysisExtent != null)
                {
                    tRasterAnalysisEnvironment.RestoreToPreviousDefaultEnvironment();
                }
                // change it to a polygon feature (will have the area added) and return it
                IGeoDataset tWatershedPolygonGDS = ConvertAndUnionWatershed(watershedRaster);
                KeyValuePair<IGeoDataset, IGeoDataset> tRasterPolyPair = new KeyValuePair<IGeoDataset, IGeoDataset>(watershedRaster, tWatershedPolygonGDS);
                return tRasterPolyPair;
            }
            catch (Exception e)
            {
                logger.LogMessage(ServerLogger.msgType.infoStandard, "Compute watershed error: ", 8000, e.Message);
                logger.LogMessage(ServerLogger.msgType.infoStandard, "Compute watershed error: ", 8000, e.ToString());
                logger.LogMessage(ServerLogger.msgType.infoStandard, "Compute watershed error: ", 8000, e.TargetSite.Name);
                logger.LogMessage(ServerLogger.msgType.infoStandard, "Compute watershed error: ", 8000, e.StackTrace);
            }
            return new KeyValuePair<IGeoDataset, IGeoDataset>();
        }
        private void zoom2selBtn_Click(object sender, EventArgs e)
        {
            if (mouseCmd == null || csvDataGrid.SelectedRows.Count == 0) return;

            int maxCount = 30;
            int i = 0;

            try
            {
                clearGraphics();

                IPointCollection points = new MultipointClass();

                foreach (DataGridViewRow row in csvDataGrid.SelectedRows)
                {
                    if (row.Cells["validAdres"].Value == null || row.Cells["validAdres"].Value.ToString() == "")
                        continue;

                    if( i > maxCount ) break;
                    i++;

                    string adres = row.Cells["validAdres"].Value.ToString();

                    string[] xy = adres.Split(new string[] {"|"}, StringSplitOptions.RemoveEmptyEntries);

                    double x; double y;
                    string adresType = "Manueel";
                    if (xy.Count() == 2)
                    {
                        bool xBool = Double.TryParse(xy[0], out x);
                        bool yBool = Double.TryParse(xy[1], out y);

                        if (!xBool || !yBool)
                        {
                            List<datacontract.locationResult> locs = loc.getAdresLocation(adres, 1);
                            if (locs.Count == 0) continue;
                            x = locs[0].Location.X_Lambert72;
                            y = locs[0].Location.Y_Lambert72;
                            adresType = locs[0].LocationType;
                        }
                    }
                    else
                    {
                        List<datacontract.locationResult> locs = loc.getAdresLocation(adres, 1);
                        if (locs.Count == 0) continue;
                        x = locs[0].Location.X_Lambert72;
                        y = locs[0].Location.Y_Lambert72;
                        adresType = locs[0].LocationType;
                    }

                    IPoint pt = new PointClass() { X = x, Y = y, SpatialReference = lam72 };
                    IPoint prjPt = geopuntHelper.Transform(pt, map.SpatialReference) as IPoint;
                    points.AddPoint(prjPt);

                    IRgbColor rgb = new RgbColorClass() { Red = 0, Blue = 255, Green = 255 };
                    IRgbColor black = new RgbColorClass() { Red = 0, Green = 0, Blue = 0 };
                    IElement grp = geopuntHelper.AddGraphicToMap(map, (IGeometry)prjPt, rgb, black, 5, true);
                    graphics.Add(grp);
                }

                if (points.PointCount == 0)
                {
                    return;
                }
                else if (points.PointCount == 1)
                {
                    IPoint xy = points.get_Point(0);
                    geopuntHelper.ZoomByRatioAndRecenter(view, 1, xy.X, xy.Y);
                    map.MapScale = 1000;
                    view.Refresh();
                }
                else
                {
                    IEnvelope extent = ((IGeometry)points).Envelope;
                    view.Extent = extent;
                    view.Refresh();
                }
            }
            catch (WebException wex)
            {
                if (wex.Status == WebExceptionStatus.Timeout)
                    MessageBox.Show("De connectie werd afgebroken." +
                        " Het duurde te lang voor de server een resultaat terug gaf.\n" +
                        "U kunt via de instellingen de 'timout'-tijd optrekken.", wex.Message);
                else if (wex.Response != null)
                {
                    string resp = new StreamReader(wex.Response.GetResponseStream()).ReadToEnd();
                    MessageBox.Show(resp, wex.Message);
                }
                else
                    MessageBox.Show(wex.Message, "Error");
            }
            catch (Exception ex)
            {
                 MessageBox.Show( ex.Message +" : "+ ex.StackTrace );
            }
        }
Example #27
0
 private void CreateMultiPoint(string filename)
 {
     try
     {
         using (StreamReader reader = new StreamReader(filename))
         {
             string           str;
             int              num    = 0;
             IPointCollection points = new MultipointClass();
             object           before = Missing.Value;
             while ((str = reader.ReadLine()) != null)
             {
                 string str2;
                 IPoint inPoint = new PointClass();
                 num++;
                 string[] strArray = str.Split(new char[] { ',' });
                 try
                 {
                     if (strArray.Length < 2)
                     {
                         str2 = filename + " 中第 " + num.ToString() + "行数据有错误";
                         Logger.Current.Error("", null, str2);
                         continue;
                     }
                     inPoint.X = double.Parse(strArray[0]);
                     inPoint.Y = double.Parse(strArray[1]);
                     if (strArray.Length > 2)
                     {
                         inPoint.Z = double.Parse(strArray[2]);
                     }
                     if (strArray.Length > 3)
                     {
                         inPoint.M = double.Parse(strArray[3]);
                     }
                     points.AddPoint(inPoint, ref before, ref before);
                 }
                 catch
                 {
                     str2 = filename + " 中第 " + num.ToString() + "行数据有错误";
                     Logger.Current.Error("", null, str2);
                 }
             }
             this.SetZMProperty(points as IGeometry);
             IFeature feature =
                 Yutai.ArcGIS.Common.Editor.Editor.CurrentEditTemplate.FeatureLayer.FeatureClass.CreateFeature();
             try
             {
                 feature.Shape = points as IGeometry;
                 feature.Store();
             }
             catch (Exception exception)
             {
                 feature.Delete();
                 Logger.Current.Error("", exception, "");
             }
             IActiveView pMap = (IActiveView)this.m_pMap;
             this.m_pMap.ClearSelection();
             this.m_pMap.SelectFeature(Yutai.ArcGIS.Common.Editor.Editor.CurrentEditTemplate.FeatureLayer,
                                       feature);
             pMap.Refresh();
         }
     }
     catch (Exception exception2)
     {
         Logger.Current.Error("", exception2, "");
     }
 }
Example #28
0
        /// <summary>
        /// �������
        /// </summary>
        /// <params name="CurPoint"></params>
        /// <returns></returns>
        private double CaculateArea(IPoint CurPoint)
        {
            IPointCollection tempCollection = new MultipointClass();

            object missing = Type.Missing;
            for (int i = 0; i < m_ptCollection.PointCount; i++)
            {
                IPoint dPoint = m_ptCollection.get_Point(i);
                tempCollection.AddPoint(dPoint, ref  missing, ref  missing);
            }

            tempCollection.AddPoint(CurPoint, ref missing, ref missing);
            tempCollection.AddPoint(tempCollection.get_Point(0), ref missing, ref  missing);
            int Count = tempCollection.PointCount;

            double x1, x2, y1, y2;
            double tempArea = 0.0;
            for (int i = 0; i < Count - 1; i++)
            {
                x1 = Convert.ToDouble(tempCollection.get_Point(i).X);
                y1 = Convert.ToDouble(tempCollection.get_Point(i).Y);
                x2 = Convert.ToDouble(tempCollection.get_Point(i + 1).X);
                y2 = Convert.ToDouble(tempCollection.get_Point(i + 1).Y);
                tempArea += (x1 * y2 - x2 * y1);
            }

            tempArea = Math.Abs(tempArea) / 2;
            return tempArea;
        }
        //从点图层中收集所有点
        public IPointCollection ReadPoint(IFeatureLayer pFeatureLayer)
        {
            IFeatureCursor pFeatureCursor = pFeatureLayer.Search(null, false);

            //获取数据库或者单个文件的第一个属性字段
            IFeature pFeature = pFeatureCursor.NextFeature();
            IField   pField   = null;

            if (pFeatureLayer.FeatureClass.Fields.FindField("FID") != -1)
            {
                pField = pFeatureLayer.FeatureClass.Fields.get_Field(pFeatureLayer.FeatureClass.Fields.FindField("FID"));
            }
            else if (pFeatureLayer.FeatureClass.Fields.FindField("OBJECTID") != -1)
            {
                pField = pFeatureLayer.FeatureClass.Fields.get_Field(pFeatureLayer.FeatureClass.Fields.FindField("OBJECTID"));
            }

            //第一个属性字段名称
            string FirstFieldName = pField.AliasName;

            IQueryFilter pQueryFilter = new QueryFilterClass();

            pQueryFilter.WhereClause = FirstFieldName + ">=0";
            int number = pFeatureLayer.FeatureClass.FeatureCount(pQueryFilter);

            //DataTable dt = AOFunctions.GDB.ITableUtil.GetDataTableFromITable(pFeatureLayer.FeatureClass as ITable, "");
            //DataAlignment.DataAlignment.CanlculateDistanceInMiddlePointTable(dt);

            CustomizedControls.StatusForm frm = new CustomizedControls.StatusForm();
            frm.StartPosition = FormStartPosition.CenterScreen;
            frm.Show();



            IPointCollection pPointCollection = new MultipointClass();
            IPoint           PrevPT           = null;

            try
            {
                for (int i = 0; i < number; i++)
                {
                    Application.DoEvents();
                    frm.Status = "处理点 " + i.ToString() + "/ " + number.ToString();
                    IGeometry pGeometry = pFeature.Shape as IGeometry;
                    IPoint    pt        = pGeometry as IPoint;
                    IPoint    pPoint    = new PointClass();

                    IZAware zpt = pPoint as IZAware;
                    zpt.ZAware = true;
                    IMAware mpt = pPoint as IMAware;
                    mpt.MAware = true;

                    pPoint.PutCoords(pt.X, pt.Y);
                    pPoint.Z = Convert.ToDouble(pFeature.Value[pFeature.Fields.FindField(EvConfig.CenterlineZField)]);

                    if (i == 0)
                    {
                        pPoint.M = 0;
                        PrevPT   = pPoint;
                    }
                    else
                    {
                        pPoint.M = PrevPT.M + DataAlignment.DataAlignment.CalculateDistanceBetween84TwoPoints(pPoint, PrevPT);

                        PrevPT = pPoint;
                    }
                    pPointCollection.AddPoint(pPoint);

                    pFeature.Value[pFeature.Fields.FindField(EvConfig.CenterlineMeasureField)] = pPoint.M;
                    pFeature.Store();

                    frm.Progress = Convert.ToInt16(Convert.ToDouble(i) / Convert.ToDouble(number) * 100);

                    pFeature = pFeatureCursor.NextFeature();
                }
            }
            catch (SystemException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                frm.Close();
            }


            return(pPointCollection);
        }
        private void btOK_Click(object sender, EventArgs e)
        {
            if (cboBoxPointLayer.SelectedItem == null)
            {
                MessageBox.Show("请加载点图层!");
                return;
            }
            if (txtLineFilePath.Text == "")
            {
                MessageBox.Show("请输入要输出线图层的路径及名称!");
                return;
            }
            try
            {
                //从点图层中读取所有点
                string pPointFileName = cboBoxPointLayer.SelectedItem.ToString();
                ILayer pLayer         = null;
                for (int i = 0; i < pMapcontrol.LayerCount; i++)
                {
                    if (pPointFileName == pMapcontrol.get_Layer(i).Name)
                    {
                        pLayer = pMapcontrol.get_Layer(i);
                    }
                }
                psf = ((IGeoDataset)pLayer).SpatialReference;
                IFeatureLayer    pFeatureLayerPoint = pLayer as IFeatureLayer;
                IPointCollection PointCollection    = ReadPoint(pFeatureLayerPoint);

                //判断需要生成的线文件是否存在,若不存在则创建文件,若存在则将新添加的线写入文件
                if (File.Exists(txtLineFilePath.Text))
                {
                    //若已经存在则读取结尾点并加入到PointCollection
                    string pLineFile = txtLineFilePath.Text;
                    string pFilePath = System.IO.Path.GetDirectoryName(pLineFile);
                    string pFileName = System.IO.Path.GetFileName(pLineFile);

                    //打开工作空间
                    IWorkspaceFactory pWSF = new ShapefileWorkspaceFactoryClass();
                    IFeatureWorkspace pWS  = (IFeatureWorkspace)pWSF.OpenFromFile(pFilePath, 0);

                    IFeatureLayer pFeatureLayer = new FeatureLayerClass();
                    pFeatureLayer.FeatureClass = pWS.OpenFeatureClass(pFileName);

                    IField pField = null;
                    if (pFeatureLayer.FeatureClass.Fields.FindField("FID") != -1)
                    {
                        pField = pFeatureLayer.FeatureClass.Fields.get_Field(pFeatureLayer.FeatureClass.Fields.FindField("FID"));
                    }
                    else if (pFeatureLayer.FeatureClass.Fields.FindField("OBJECTID") != -1)
                    {
                        pField = pFeatureLayer.FeatureClass.Fields.get_Field(pFeatureLayer.FeatureClass.Fields.FindField("OBJECTID"));
                    }
                    //第一个属性字段名称
                    string       FirstFieldName = pField.AliasName;
                    IQueryFilter pQueryFilter   = new QueryFilterClass();
                    pQueryFilter.WhereClause = FirstFieldName + ">=0";
                    int number = pFeatureLayer.FeatureClass.FeatureCount(pQueryFilter);

                    IFeature pFeature;
                    if (FirstFieldName == "FID")
                    {
                        pFeature = pFeatureLayer.FeatureClass.GetFeature(number - 1);
                    }
                    else
                    {
                        pFeature = pFeatureLayer.FeatureClass.GetFeature(number);
                    }
                    IGeometry pGeometry = pFeature.Shape as IGeometry;
                    IPolyline pPolyline = pGeometry as IPolyline;

                    IPointCollection pPointCollection = new MultipointClass();
                    pPointCollection.AddPoint(pPolyline.ToPoint);

                    PointCollection.InsertPointCollection(0, pPointCollection);
                }
                else
                {
                    //不存在则创建新的线图层
                    CreateNewLineLayer();
                }

                //将所有的点连接成线
                IPolyline Polyline = CreatePolyline(PointCollection);

                //将连接成的线添加到线图层中
                AddFeature(Polyline as IGeometry);

                MessageBox.Show("成功生成中线");

                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        /// <summary>
        /// 根据输入的一系列点计算voronoi图
        /// </summary>
        /// <param name="points">一系列点</param>
        /// <returns>一系列多变形</returns>
        public static IList <IGeometry> GeometryVoronoi(List <IPoint> points)
        {
            // 判断点的数量是否合法
            if (points.Count < 3)
            {
                throw new ArgumentException("Input must be a MultiPoint containing at least three points");
            }

            // 初始化顶点列表
            List <SimplePoint> vertices = new List <SimplePoint>();

            // 加入所有初始提供的点
            for (int i = 0; i < points.Count; i++)
            {
                SimplePoint point = new SimplePoint(points[i].X, points[i].Y);

                // 除掉所有的多点,因为三角剖分算法不支持多点的引入
                if (!vertices.Contains(point))
                {
                    vertices.Add(point);
                }
            }

            // 计算点集的数量,此时应该已经除掉了所有的重复点
            int numPoints = vertices.Count;

            // 判断点的数量是否合法
            if (numPoints < 3)
            {
                throw new ArgumentException("Input must be a list of points containing at least three points");
            }

            // 基于vertices中的顶点x坐标对indices进行sort
            vertices.Sort();

            IPointCollection pointCollection = new MultipointClass();

            foreach (SimplePoint p in vertices)
            {
                pointCollection.AddPoint(new PointClass()
                {
                    X = p.X, Y = p.Y
                });
            }


            IEnvelope envelope = (pointCollection as IGeometry).Envelope;

            // Width
            double dx = envelope.Width;

            // Height
            double dy = envelope.Height;

            // Maximum dimension
            double dmax = (dx > dy) ? dx : dy;

            // Centre
            double avgx = ((envelope.XMax - envelope.XMin) / 2) + envelope.XMin;
            double avgy = ((envelope.YMax - envelope.YMin) / 2) + envelope.YMin;

            // Create the points at corners of the supertriangle
            SimplePoint a = new SimplePoint(avgx - (2 * dmax), avgy - dmax);
            SimplePoint b = new SimplePoint(avgx + (2 * dmax), avgy - dmax);
            SimplePoint c = new SimplePoint(avgx, avgy + (2 * dmax));

            // Add the supertriangle vertices to the end of the vertex array
            vertices.Add(a);
            vertices.Add(b);
            vertices.Add(c);

            double      radius;
            SimplePoint circumcentre;

            Triangulation.CalculateCircumcircle(a, b, c, out circumcentre, out radius);

            // 确定超级三角形,这个三角形应该包含所有点
            SimpleTriangle superTriangle = new SimpleTriangle(numPoints, numPoints + 1, numPoints + 2, circumcentre, radius);

            // 将超级三角形push到triangles列表
            List <SimpleTriangle> triangles = new List <SimpleTriangle>();

            triangles.Add(superTriangle);

            List <SimpleTriangle> completedTriangles = new List <SimpleTriangle>();

            // 遍历基于indecies顺序的vertices中的每一个点
            for (int i = 0; i < numPoints; i++)
            {
                // 初始化边缓存数组
                List <int[]> edges = new List <int[]>();

                // 遍历temp triangles中的每一个三角形
                for (int j = triangles.Count - 1; j >= 0; j--)
                {
                    // 如果该点在外接圆内
                    if (Distance(triangles[j].CircumCentre, vertices[i]) < triangles[j].Radius)
                    {
                        // 则该三角形不为Delaunay三角形,将三边保存至edge buffer
                        edges.Add(new int[] { triangles[j].A, triangles[j].B });
                        edges.Add(new int[] { triangles[j].B, triangles[j].C });
                        edges.Add(new int[] { triangles[j].C, triangles[j].A });

                        // 在temp中除掉该三角形
                        triangles.RemoveAt(j);
                    }
                    else if (vertices[i].X > triangles[j].CircumCentre.X + triangles[j].Radius)
                    {
                        {
                            completedTriangles.Add(triangles[j]);
                        }

                        triangles.RemoveAt(j);
                    }
                }

                // 对edgebuffer进行去重
                for (int j = edges.Count - 1; j > 0; j--)
                {
                    for (int k = j - 1; k >= 0; k--)
                    {
                        // Compare if this edge match in either direction
                        if (edges[j][0].Equals(edges[k][1]) && edges[j][1].Equals(edges[k][0]))
                        {
                            // 去重
                            edges.RemoveAt(j);
                            edges.RemoveAt(k);

                            // We've removed an item from lower down the list than where j is now, so update j
                            j--;
                            break;
                        }
                    }
                }

                // Create new triangles for the current point
                for (int j = 0; j < edges.Count; j++)
                {
                    Triangulation.CalculateCircumcircle(vertices[edges[j][0]], vertices[edges[j][1]], vertices[i], out circumcentre, out radius);
                    SimpleTriangle t = new SimpleTriangle(edges[j][0], edges[j][1], i, circumcentre, radius);
                    triangles.Add(t);
                }
            }

            // 我们已经完成了三角剖分部分,接下来就是要完成构建voronoi图的过程
            completedTriangles.AddRange(triangles);

            IList <IGeometry> voronoiPolygon = new List <IGeometry>();

            for (var i = 0; i < vertices.Count; i++)
            {
                // 新建一个IGeometry来存放voronoi图
                IPointCollection mp = new MultipointClass();

                // 遍历所有三角形
                foreach (SimpleTriangle tri in completedTriangles)
                {
                    // If the triangle intersects this point
                    if (tri.A == i || tri.B == i || tri.C == i)
                    {
                        mp.AddPoint(new PointClass()
                        {
                            X = tri.CircumCentre.X, Y = tri.CircumCentre.Y
                        });
                    }
                }

                // Create the voronoi polygon from the convex hull of the circumcentres of intersecting triangles
                ITopologicalOperator topologicalOperator = mp as ITopologicalOperator;
                IGeometry            polygon             = topologicalOperator.ConvexHull();
                topologicalOperator = polygon as ITopologicalOperator;
                IGeometry result = topologicalOperator.Intersect(envelope, esriGeometryDimension.esriGeometry2Dimension);
                if ((result != null) && (!result.IsEmpty))
                {
                    voronoiPolygon.Add(result);
                }
            }

            return(voronoiPolygon);
        }
Example #32
0
        /// <summary>
        /// Calculate diagram voronoi from list of points
        /// </summary>
        /// <param name="points">list of points</param>
        /// <returns>list of polygons</returns>
        public static IList<IGeometry> GeometryVoronoi(List<IPoint> points)
        {
            // Check valid input
            if (points.Count < 3)
            {
                throw new ArgumentException("Input must be a MultiPoint containing at least three points");
            }

            // Initialise a list of vertices
            List<SimplePoint> vertices = new List<SimplePoint>();

            // Add all the original supplied points
            for (int i = 0; i < points.Count; i++)
            {
                SimplePoint point = new SimplePoint(points[i].X, points[i].Y);

                // MultiPoints can contain the same point twice, but this messes up Delaunay
                if (!vertices.Contains(point))
                {
                    vertices.Add(point);
                }
            }

            // Important - count the number of points in the array as some duplicate points
            // may have been removed
            int numPoints = vertices.Count;

            // Check valid input
            if (numPoints < 3)
            {
                throw new ArgumentException("Input must be a list of points containing at least three points");
            }

            // Important! Sort the list so that points sweep from left - right
            vertices.Sort();

            IPointCollection pointCollection = new MultipointClass();
            foreach (SimplePoint p in vertices)
            {
                pointCollection.AddPoint(new PointClass() { X = p.X, Y = p.Y });
            }

            // Calculate the "supertriangle" that encompasses the pointset
            IEnvelope envelope = (pointCollection as IGeometry).Envelope;

            // Width
            double dx = envelope.Width;

            // Height
            double dy = envelope.Height;

            // Maximum dimension
            double dmax = (dx > dy) ? dx : dy;

            // Centre
            double avgx = ((envelope.XMax - envelope.XMin) / 2) + envelope.XMin;
            double avgy = ((envelope.YMax - envelope.YMin) / 2) + envelope.YMin;

            // Create the points at corners of the supertriangle
            SimplePoint a = new SimplePoint(avgx - (2 * dmax), avgy - dmax);
            SimplePoint b = new SimplePoint(avgx + (2 * dmax), avgy - dmax);
            SimplePoint c = new SimplePoint(avgx, avgy + (2 * dmax));

            // Add the supertriangle vertices to the end of the vertex array
            vertices.Add(a);
            vertices.Add(b);
            vertices.Add(c);

            double radius;
            SimplePoint circumcentre;
            Triangulation.CalculateCircumcircle(a, b, c, out circumcentre, out radius);

            // Create a triangle from the vertices
            SimpleTriangle superTriangle = new SimpleTriangle(numPoints, numPoints + 1, numPoints + 2, circumcentre, radius);

            // Add the supertriangle to the list of triangles
            List<SimpleTriangle> triangles = new List<SimpleTriangle>();
            triangles.Add(superTriangle);

            List<SimpleTriangle> completedTriangles = new List<SimpleTriangle>();

            // Loop through each point
            for (int i = 0; i < numPoints; i++)
            {
                // Initialise the edge buffer
                List<int[]> edges = new List<int[]>();

                // Loop through each triangle
                for (int j = triangles.Count - 1; j >= 0; j--)
                {
                    // If the point lies within the circumcircle of this triangle
                    if (Distance(triangles[j].CircumCentre, vertices[i]) < triangles[j].Radius)
                    {
                        // Add the triangle edges to the edge buffer
                        edges.Add(new int[] { triangles[j].A, triangles[j].B });
                        edges.Add(new int[] { triangles[j].B, triangles[j].C });
                        edges.Add(new int[] { triangles[j].C, triangles[j].A });

                        // Remove this triangle from the list
                        triangles.RemoveAt(j);
                    }
                    else if (vertices[i].X > triangles[j].CircumCentre.X + triangles[j].Radius)
                    {
                        // If this triangle is complete
                        {
                            completedTriangles.Add(triangles[j]);
                        }

                        triangles.RemoveAt(j);
                    }
                }

                // Remove duplicate edges
                for (int j = edges.Count - 1; j > 0; j--)
                {
                    for (int k = j - 1; k >= 0; k--)
                    {
                        // Compare if this edge match in either direction
                        if (edges[j][0].Equals(edges[k][1]) && edges[j][1].Equals(edges[k][0]))
                        {
                            // Remove both duplicates
                            edges.RemoveAt(j);
                            edges.RemoveAt(k);

                            // We've removed an item from lower down the list than where j is now, so update j
                            j--;
                            break;
                        }
                    }
                }

                // Create new triangles for the current point
                for (int j = 0; j < edges.Count; j++)
                {
                    Triangulation.CalculateCircumcircle(vertices[edges[j][0]], vertices[edges[j][1]], vertices[i], out circumcentre, out radius);
                    SimpleTriangle t = new SimpleTriangle(edges[j][0], edges[j][1], i, circumcentre, radius);
                    triangles.Add(t);
                }
            }

            // We've finished triangulation. Move any remaining triangles onto the completed list
            completedTriangles.AddRange(triangles);

            IList<IGeometry> voronoiPolygon = new List<IGeometry>();
            for (var i = 0; i < vertices.Count; i++)
            {
                // Initiliase a new geometry to hold the voronoi polygon
                IPointCollection mp = new MultipointClass();

                // Look through each triangle
                foreach (SimpleTriangle tri in completedTriangles)
                {
                    // If the triangle intersects this point
                    if (tri.A == i || tri.B == i || tri.C == i)
                    {
                        mp.AddPoint(new PointClass() { X = tri.CircumCentre.X, Y = tri.CircumCentre.Y });
                    }
                }

                // Create the voronoi polygon from the convex hull of the circumcentres of intersecting triangles
                ITopologicalOperator topologicalOperator = mp as ITopologicalOperator;
                IGeometry polygon = topologicalOperator.ConvexHull();
                topologicalOperator = polygon as ITopologicalOperator;
                IGeometry result = topologicalOperator.Intersect(envelope, esriGeometryDimension.esriGeometry2Dimension);
                if ((result != null) && (!result.IsEmpty))
                {
                    voronoiPolygon.Add(result);
                }
            }

            return voronoiPolygon;
        }
Example #33
0
        static void createWkbMultiLineString(byte[] wkb, ref int startIndex, BitConversion bitConversion, out IGeometry geometry)
        {
            geometry = new PolylineClass();
            IPointCollection mp = (IPointCollection)geometry;

            // Get the number of line strings.
            UInt32 lineStringCnt;
            getWkbUInt32(wkb, ref startIndex, bitConversion, out lineStringCnt);

            UInt32 pointCnt;
            double x, y;
            object missing = Type.Missing;
            // Loop through each LineString.
            for (int i = 0; i < lineStringCnt; i++)
            {
                startIndex += 5;  // Jump past useless header stuff.
                getWkbUInt32(wkb, ref startIndex, bitConversion, out pointCnt);

                IPointCollection tempPc = new MultipointClass();
                // Loop through each point.
                for (int j = 0; j < pointCnt; j++)
                {
                    getWkbDouble(wkb, ref startIndex, bitConversion, out x);
                    getWkbDouble(wkb, ref startIndex, bitConversion, out y);
                    tempPc.AddPoint(createAoPoint(x, y), ref missing, ref missing);
                }
                mp.AddPointCollection(tempPc);
            }
        }
        //从点图层中收集所有点
        public IPointCollection ReadPoint(IFeatureLayer pFeatureLayer)
        {
            IFeatureCursor pFeatureCursor = pFeatureLayer.Search(null, false);

            //获取数据库或者单个文件的第一个属性字段
            IFeature pFeature = pFeatureCursor.NextFeature();
            IField   pField   = null;

            if (pFeatureLayer.FeatureClass.Fields.FindField("FID") != -1)
            {
                pField = pFeatureLayer.FeatureClass.Fields.get_Field(pFeatureLayer.FeatureClass.Fields.FindField("FID"));
            }
            else if (pFeatureLayer.FeatureClass.Fields.FindField("OBJECTID") != -1)
            {
                pField = pFeatureLayer.FeatureClass.Fields.get_Field(pFeatureLayer.FeatureClass.Fields.FindField("OBJECTID"));
            }

            //第一个属性字段名称
            string FirstFieldName = pField.AliasName;

            IQueryFilter pQueryFilter = new QueryFilterClass();

            pQueryFilter.WhereClause = FirstFieldName + ">=0";
            int number = pFeatureLayer.FeatureClass.FeatureCount(pQueryFilter);

            //DataTable dt = AOFunctions.GDB.ITableUtil.GetDataTableFromITable(pFeatureLayer.FeatureClass as ITable, "");
            //DataAlignment.DataAlignment.CanlculateDistanceInMiddlePointTable(dt);

            IPointCollection pPointCollection = new MultipointClass();
            IPoint           PrevPT           = null;

            for (int i = 0; i < number; i++)
            {
                IGeometry pGeometry = pFeature.Shape as IGeometry;
                IPoint    pt        = pGeometry as IPoint;
                IPoint    pPoint    = new PointClass();

                IZAware zpt = pPoint as IZAware;
                zpt.ZAware = true;
                IMAware mpt = pPoint as IMAware;
                mpt.MAware = true;

                pPoint.PutCoords(pt.X, pt.Y);
                pPoint.Z = Convert.ToDouble(pFeature.Value[pFeature.Fields.FindField(EvConfig.CenterlineZField)]);

                if (i == 0)
                {
                    pPoint.M = 0;
                    PrevPT   = pPoint;
                }
                else
                {
                    pPoint.M = PrevPT.M + DataAlignment.DataAlignment.CalculateDistanceBetween84TwoPoints(pPoint, PrevPT);

                    PrevPT = pPoint;
                }
                pPointCollection.AddPoint(pPoint);

                pFeature = pFeatureCursor.NextFeature();
            }

            return(pPointCollection);
        }
Example #35
0
        private void zoom2selBtn_Click(object sender, EventArgs e)
        {
            if (resultGrid.SelectedRows.Count == 0) return;

            IPointCollection points = new MultipointClass();
            try
            {
                for (int i = 0; i < resultGrid.SelectedRows.Count; i++)
                {
                    DataGridViewRow row = resultGrid.SelectedRows[i];
                    int id = (int)row.Cells[0].Value;

                    List<datacontract.poiLocation> qry = (from n in poiData.pois
                                                          where n.id == id
                                                          select n.location).ToList<datacontract.poiLocation>();
                    if (qry.Count == 0) break;
                    if (qry[0].points == null || qry[0].points.Count == 0) break;

                    datacontract.geojsonPoint jsonPt = qry[0].points[0].Point;
                    IPoint wgsPt = geopuntHelper.geojson2esriPoint(jsonPt, 4326);
                    IPoint prjPt = (IPoint)geopuntHelper.Transform((IGeometry)wgsPt, map.SpatialReference);

                    points.AddPoint(prjPt, Type.Missing, Type.Missing);
                }
                if (points.PointCount == 0)
                {
                    return;
                }
                else if (points.PointCount == 1)
                {
                    IPoint xy = points.get_Point(0);
                    geopuntHelper.ZoomByRatioAndRecenter(view, 1, xy.X, xy.Y);
                    map.MapScale = 1000;
                }
                else
                {
                    IEnvelope extent = ((IGeometry)points).Envelope;
                    view.Extent = extent;
                }
                view.Refresh();
            }
            catch (WebException wex)
            {
                if (wex.Status == WebExceptionStatus.Timeout)
                    MessageBox.Show("De connectie werd afgebroken." +
                        " Het duurde te lang voor de server een resultaat terug gaf.\n" +
                        "U kunt via de instellingen de 'timout'-tijd optrekken.", wex.Message);
                else if (wex.Response != null)
                {
                    string resp = new StreamReader(wex.Response.GetResponseStream()).ReadToEnd();
                    MessageBox.Show(resp, wex.Message);
                }
                else
                    MessageBox.Show(wex.Message, "Error");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ": " + ex.StackTrace);
            }
        }
        //this method is called when the user clicks the "Compare Vertices" button at the bottom of the form
        private void cmdCompare_Click(object sender, EventArgs e)
        {
            try
            {
                if (cboLayer1.SelectedItem.ToString() == "" || cboLayer2.SelectedItem.ToString() == "" || txtOID1.Text == "" || txtOID2.Text == "") //the double pipe is an or operator that "short circuts", meaning that it will bail out early if the condition is true, whereas the single pipe evaluates all conditions
                {
                    MessageBox.Show("Choose polygon layer, or specify OBJECTID.", "Verify Selections...", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                //show busy mouse
                System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;

                IFeatureLayer pFeatureLayer1 = null;
                IFeatureLayer pFeatureLayer2 = null;

                IPointCollection pPtnCollMissingVertices = new MultipointClass(); //point collection for missing vertices and used for graphics layer
                IPoint           pPointMissing           = new PointClass();      //used for graphics layer

                //get access to polygon layer 1
                for (int i = 0; i < pMap.LayerCount; i++)
                {
                    if (pMap.get_Layer(i) is IFeatureLayer)
                    {
                        if (pMap.get_Layer(i).Name.ToString() == cboLayer1.SelectedItem.ToString())
                        {
                            pFeatureLayer1 = pMap.get_Layer(i) as IFeatureLayer;
                            break;
                        }
                    }
                }

                //get access to polygon layer 2
                for (int i = 0; i < pMap.LayerCount; i++)
                {
                    if (pMap.get_Layer(i) is IFeatureLayer)
                    {
                        if (pMap.get_Layer(i).Name.ToString() == cboLayer2.SelectedItem.ToString())
                        {
                            pFeatureLayer2 = pMap.get_Layer(i) as IFeatureLayer;
                            break;
                        }
                    }
                }

                //clear the x,y report list box
                lstMissingVertices.Items.Clear();


                //get vertices for feature 1
                //set up query filter for feature 1
                IQueryFilter pQueryFilter = new QueryFilter();
                pQueryFilter.WhereClause = "OBJECTID = " + txtOID1.Text;

                //set up feature cursor for feature 1
                IFeatureCursor pFeatureCursor = pFeatureLayer1.Search(pQueryFilter, false);

                //get feature 1
                IFeature pFeature1 = pFeatureCursor.NextFeature();

                //if no objectid is found
                if (pFeature1 == null)
                {
                    MessageBox.Show("The provided OBJECTID was not found for layer: " + cboLayer1.SelectedItem, "ObjectID Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                //get feature 1 as a polygon
                IPolygon pPolygon1 = pFeature1.Shape as IPolygon;

                //get the point collection for feature 1
                IPointCollection pPointColl1 = pPolygon1 as IPointCollection;


                //get vertices for feature 2
                //set up query filter for feature 2
                pQueryFilter             = new QueryFilter();
                pQueryFilter.WhereClause = "OBJECTID = " + txtOID2.Text;

                //set up feature cursor for feature 2
                pFeatureCursor = null; //reuse the feature cursor from above
                pFeatureCursor = pFeatureLayer2.Search(pQueryFilter, false);

                //get feature 2
                IFeature pFeature2 = pFeatureCursor.NextFeature();

                //if no objectid is found
                if (pFeature2 == null)
                {
                    MessageBox.Show("The provided OBJECTID was not found for layer: " + cboLayer1.SelectedItem, "ObjectID Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                //get feature 1 as a polygon
                IPolygon pPolygon2 = pFeature2.Shape as IPolygon;

                //get the point collection for feature 1
                IPointCollection pPointColl2 = pPolygon2 as IPointCollection;


                //loop through point collection and check for missing vertices
                IPoint  pPoint1;
                IPoint  pPoint2;
                Boolean blnFound;


                //loop through each point in the first collection and check for missing
                for (int i = 0; i < pPointColl1.PointCount; i++)
                {
                    pPoint1 = pPointColl1.get_Point(i);

                    //loop through all the points in the second collection and check for the point from the above collection
                    blnFound = false;
                    for (int j = 0; j < pPointColl2.PointCount; j++)
                    {
                        pPoint2 = pPointColl2.get_Point(j);

                        //check for overlapping points
                        if (pPoint1.X == pPoint2.X && pPoint1.Y == pPoint2.Y)
                        {
                            blnFound = true;
                        }
                    }

                    //if no overlapping points were found, report the missing x,y location to the listbox
                    if (blnFound == false)
                    {
                        lstMissingVertices.Items.Add(pPoint1.X + " " + pPoint1.Y + " " + " Feet" + " (missing from polygon 2)");

                        //add the missing point to a new collection for display on map
                        pPtnCollMissingVertices.AddPoint(pPoint1);
                    }
                }


                //loop through each point in the first collection and check for missing
                for (int i = 0; i < pPointColl2.PointCount; i++)
                {
                    pPoint2 = pPointColl2.get_Point(i);

                    //loop through all the points in the second collection and check for the point from the above collection
                    blnFound = false;
                    for (int j = 0; j < pPointColl1.PointCount; j++)
                    {
                        pPoint1 = pPointColl1.get_Point(j);

                        //check for overlapping points
                        if (pPoint2.X == pPoint1.X && pPoint2.Y == pPoint1.Y)
                        {
                            blnFound = true;
                        }
                    }

                    //if no overlapping points were found, report the missing x,y location to the listbox
                    if (blnFound == false)
                    {
                        lstMissingVertices.Items.Add(pPoint2.X + " " + pPoint2.Y + " " + " Feet" + " (missing from polygon 1)");

                        //add the missing point to a new collection for display on map
                        pPtnCollMissingVertices.AddPoint(pPoint2);
                    }
                }


                //if no missing vertices were found, inform the user
                if (lstMissingVertices.Items.Count < 1)
                {
                    lstMissingVertices.Items.Add("No Missing Vertices Found");
                }


                //display vertices if checkbox is checked
                if (chkDisplayVertices.Checked == true)
                {
                    //show busy mouse
                    System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;

                    //set up the graphics layer for the display of vertices
                    ICompositeGraphicsLayer2 pCompositeGraphicLayer = pMap.BasicGraphicsLayer as ICompositeGraphicsLayer2;
                    ICompositeLayer          pCompositeLayer        = pCompositeGraphicLayer as ICompositeLayer;
                    ILayer             pLayer;
                    IGraphicsLayer     pGraphicsLayer;
                    IGraphicsContainer pGraphicsContainer;

                    //loop through the graphics layer and check for the missing vertices layer.  if found, delete it
                    for (int i = 0; i < pCompositeLayer.Count; i++)
                    {
                        pLayer = pCompositeLayer.Layer[i];
                        if (pLayer.Name == "MissingVertices")
                        {
                            pCompositeGraphicLayer.DeleteLayer("MissingVertices");
                            break;
                        }
                    }


                    //set up a new 'missing vertices' graphics layer
                    pGraphicsLayer           = pCompositeGraphicLayer.AddLayer("MissingVertices", null);
                    pMap.ActiveGraphicsLayer = pGraphicsLayer as ILayer;
                    pGraphicsContainer       = pCompositeGraphicLayer.FindLayer("MissingVertices") as IGraphicsContainer;

                    //define the color
                    ESRI.ArcGIS.Display.IRgbColor rgbColorCls = new ESRI.ArcGIS.Display.RgbColorClass();
                    rgbColorCls.Red   = 250;
                    rgbColorCls.Green = 0;
                    rgbColorCls.Blue  = 0;

                    //define the font
                    stdole.IFontDisp stdFontCls = new stdole.StdFontClass() as stdole.IFontDisp;
                    stdFontCls.Name = "ESRI Surveyor Marker"; //this one has a thin-line hollow circle
                    stdFontCls.Name = "ESRI Surveyor";        //this one has a bold-line hollow circle
                    stdFontCls.Size = 16;

                    //set the character marker symbol's properties
                    ESRI.ArcGIS.Display.ICharacterMarkerSymbol charMarkerSymb = new ESRI.ArcGIS.Display.CharacterMarkerSymbolClass();
                    charMarkerSymb.Angle          = 0;
                    charMarkerSymb.CharacterIndex = 47;
                    charMarkerSymb.Color          = rgbColorCls;
                    charMarkerSymb.Font           = stdFontCls;
                    charMarkerSymb.Size           = 16;
                    charMarkerSymb.XOffset        = 0;
                    charMarkerSymb.YOffset        = 0;

                    //place the graphics on the map
                    for (int i = 0; i < pPtnCollMissingVertices.PointCount; i++)
                    {
                        pPointMissing = pPtnCollMissingVertices.Point[i];
                        IElement pElement = new MarkerElement();
                        pElement.Geometry = pPointMissing;
                        IMarkerElement pMarkerElement = pElement as IMarkerElement;
                        pMarkerElement.Symbol = charMarkerSymb;
                        pGraphicsContainer.AddElement(pElement, 0);
                    }

                    //refresh the map, in order to see the newly added graphics
                    pActiveView.Refresh();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Message: " + Environment.NewLine + ex.Message + Environment.NewLine + Environment.NewLine +
                                "Error Source: " + Environment.NewLine + ex.Source + Environment.NewLine + Environment.NewLine +
                                "Error Location:" + Environment.NewLine + ex.StackTrace,
                                "AGRC Custom Tools ArcMap Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        private void SetPINValue()
        {
            //The Theory.
            //Select polygons that intersect the sketch.
            //Construct one polyline from the boundaries and intersect with sketch.
            //Sort resulting intersection locations (multipoint) by distance of the intersect
            // from the start of the sketch and create new ordered multipoint.
            //Loop through new ordered multipoint, select underlying parcel and calc pin.

            IFeatureLayer featLayer = m_editLayers.CurrentLayer;

            m_curve = m_edSketch.Geometry as IPolyline;

            //Search parcel polys by graphic to get feature cursor
            ISpatialFilter spatialFilter = new SpatialFilter();

            spatialFilter.Geometry      = m_curve;
            spatialFilter.GeometryField = m_editLayers.CurrentLayer.FeatureClass.ShapeFieldName;
            spatialFilter.SpatialRel    = esriSpatialRelEnum.esriSpatialRelCrosses;

            IFeatureCursor featCursor = featLayer.Search(spatialFilter, true);
            IFeature       feature    = featCursor.NextFeature();

            //If we have no intersects then exit
            if (feature == null)
            {
                return;
            }

            //Make a GeomBag of the polygons boundaries (polylines)
            IGeometryCollection geomBag = new GeometryBagClass();
            object missing = Type.Missing;

            while (feature != null)
            {
                ITopologicalOperator poly = feature.Shape as ITopologicalOperator;
                geomBag.AddGeometry(poly.Boundary, ref missing, ref missing);
                feature = featCursor.NextFeature();
            }

            //Make one polyline from the boundaries
            IPolyline            polyLineU = new PolylineClass();
            ITopologicalOperator topoOp    = polyLineU as ITopologicalOperator;

            topoOp.ConstructUnion(geomBag as IEnumGeometry);

            //Get the intersections of the boundaries and the curve
            IPointCollection pointCol = topoOp.Intersect(m_curve, esriGeometryDimension.esriGeometry0Dimension) as IPointCollection;

            //The point collection is not ordered by distance along the curve so
            //need to create a new collection with this info

            int[]  pointOrder = new int[pointCol.PointCount];
            double dac = 0, dfc = 0;
            bool   bRS = false;

            for (int i = 0; i < pointCol.PointCount; i++)
            {
                IPoint queryPoint = new PointClass();
                pointCol.QueryPoint(i, queryPoint);
                m_curve.QueryPointAndDistance(esriSegmentExtension.esriNoExtension, queryPoint, false, null, ref dac, ref dfc, ref bRS);
                pointOrder[i] = (int)dac;
            }

            //use built in bubble sort
            System.Array.Sort(pointOrder);

            //Loop through the sorted array and calc midpoint between parcel boundaries
            IPointCollection midPoints = new MultipointClass();

            for (int i = 0; i < pointOrder.Length - 1; i++)
            {
                //Get the midpoint distance
                double midPointDist = (pointOrder[i] + pointOrder[i + 1]) / 2;

                //create a point at the distance and store in point collection
                IPoint queryPoint = new PointClass();
                m_curve.QueryPoint(esriSegmentExtension.esriNoExtension, midPointDist, false, queryPoint);
                midPoints.AddPoint(queryPoint, ref missing, ref missing);
            }

            //If ends of sketch are included then add them as points
            if (chkEnds.Checked)
            {
                object before = 0 as object;
                midPoints.AddPoint(m_curve.FromPoint, ref before, ref missing);
                midPoints.AddPoint(m_curve.ToPoint, ref missing, ref missing);
            }

            m_editor.StartOperation();

            //Loop through calculated midpoints, select polygon and calc pin
            for (int i = 0; i < midPoints.PointCount; i++)
            {
                IPoint midPoint = midPoints.get_Point(i);
                spatialFilter               = new SpatialFilter();
                spatialFilter.Geometry      = midPoint;
                spatialFilter.GeometryField = m_editLayers.CurrentLayer.FeatureClass.ShapeFieldName;
                spatialFilter.SpatialRel    = esriSpatialRelEnum.esriSpatialRelWithin;

                featCursor = featLayer.Search(spatialFilter, false);
                while ((feature = featCursor.NextFeature()) != null)
                {
                    feature.set_Value(feature.Fields.FindField(cmbPINField.Text), m_lotNum);
                    feature.Store();
                    m_lotNum += int.Parse(txtlotinc.Text);
                }
            }
            m_editor.StopOperation("ViperPIN");
            txtlot.Text = m_lotNum.ToString();
        }
Example #38
0
        //几何图形坐标转换
        private void GeometryCoordConvert(ref IGeometry pConvertGeometry, double A1, double B1, double C1, double A2, double B2, double C2, double A3, double C3)
        {
            object a      = System.Reflection.Missing.Value;
            object b      = System.Reflection.Missing.Value;
            bool   isRing = false;

            if (pConvertGeometry.GeometryType != esriGeometryType.esriGeometryPoint)//如果为线要素或面要素
            {
                IArray pArrayPoint    = new ArrayClass();
                IArray pGeometryArray = new ArrayClass();
                IGeometryCollection pGeometryCollection = pConvertGeometry as IGeometryCollection;
                for (int i = 0; i < pGeometryCollection.GeometryCount; i++)
                {
                    IGeometry pGeometry = pGeometryCollection.get_Geometry(i);
                    if (pGeometry.GeometryType != esriGeometryType.esriGeometryPoint)//
                    {
                        #region
                        if (pGeometry.GeometryType == esriGeometryType.esriGeometryRing)
                        {
                            isRing = true;
                        }

                        if (pGeometry.GeometryType == esriGeometryType.esriGeometryPolygon)
                        {
                            pGeometry = CommonFunction.GetPolygonBoundary((IPolygon)pGeometry);
                        }

                        ISegmentCollection pSegmentCol    = (ISegmentCollection)pGeometry;
                        ISegmentCollection pNewSegmentCol = new PolylineClass();
                        for (int k = 0; k < pSegmentCol.SegmentCount; k++)//遍历几何形体的每个节(片断)
                        {
                            //该节为直线段
                            if (pSegmentCol.get_Segment(k).GeometryType == esriGeometryType.esriGeometryLine)
                            {
                                IPointCollection pPointCol1 = new MultipointClass();
                                ILine            pLine      = (ILine)pSegmentCol.get_Segment(k);

                                IPoint pFromPoint = pLine.FromPoint;
                                pPointCol1.AddPoint((IPoint)pFromPoint, ref a, ref b);
                                IPoint pToPoint = pLine.ToPoint;
                                pPointCol1.AddPoint((IPoint)pToPoint, ref a, ref b);

                                PointCollCoordConvert(A1, B1, C1, A2, B2, C2, A3, C3, ref pPointCol1);//对点集做镜像

                                //修改线段的端点坐标
                                pLine.FromPoint = pPointCol1.get_Point(0);
                                pLine.ToPoint   = pPointCol1.get_Point(1);

                                pNewSegmentCol.AddSegment((ISegment)pLine, ref a, ref b);
                            }
                            //该节为圆弧
                            else if (pSegmentCol.get_Segment(k).GeometryType == esriGeometryType.esriGeometryCircularArc)
                            {
                                IPointCollection pPointCol2 = new MultipointClass();

                                ICircularArc pCircularArc = (ICircularArc)pSegmentCol.get_Segment(k);

                                try
                                {
                                    IPoint pCenterPoint = pCircularArc.CenterPoint;
                                    pPointCol2.AddPoint((IPoint)pCenterPoint, ref a, ref b);
                                    IPoint pFromPoint = pCircularArc.FromPoint;
                                    pPointCol2.AddPoint((IPoint)pFromPoint, ref a, ref b);
                                    IPoint pToPoint = pCircularArc.ToPoint;
                                    pPointCol2.AddPoint((IPoint)pToPoint, ref a, ref b);

                                    PointCollCoordConvert(A1, B1, C1, A2, B2, C2, A3, C3, ref pPointCol2);//对点集做镜像

                                    //构造新的圆弧
                                    ICircularArc pArc = new CircularArcClass();
                                    pArc.PutCoords(pPointCol2.get_Point(0), pPointCol2.get_Point(1), pPointCol2.get_Point(2),
                                                   (pCircularArc.IsCounterClockwise ? esriArcOrientation.esriArcCounterClockwise : esriArcOrientation.esriArcClockwise));

                                    pNewSegmentCol.AddSegment((ISegment)pArc, ref a, ref b);
                                }
                                catch { }
                            }
                            //该节为贝塞尔曲线
                            else if (pSegmentCol.get_Segment(k).GeometryType == esriGeometryType.esriGeometryBezier3Curve)
                            {
                                IPointCollection pPointCol3   = new MultipointClass();
                                IBezierCurve     pBezierCurve = (IBezierCurve)pSegmentCol.get_Segment(k);

                                //记录该节贝塞尔曲线的4个控制点
                                IPoint pFromPoint = new PointClass();
                                pBezierCurve.QueryCoord(0, pFromPoint);
                                pPointCol3.AddPoint(pFromPoint, ref a, ref b);
                                IPoint pFromTangentPoint = new PointClass();
                                pBezierCurve.QueryCoord(1, pFromTangentPoint);
                                pPointCol3.AddPoint(pFromTangentPoint, ref a, ref b);
                                IPoint pToTangentPoint = new PointClass();
                                pBezierCurve.QueryCoord(2, pToTangentPoint);
                                pPointCol3.AddPoint(pToTangentPoint, ref a, ref b);
                                IPoint pToPoint = new PointClass();
                                pBezierCurve.QueryCoord(3, pToPoint);
                                pPointCol3.AddPoint(pToPoint, ref a, ref b);

                                PointCollCoordConvert(A1, B1, C1, A2, B2, C2, A3, C3, ref pPointCol3);//对点集做镜像

                                //修改该节贝塞尔曲线的4个控制点
                                pBezierCurve.PutCoord(0, pPointCol3.get_Point(0));
                                pBezierCurve.PutCoord(1, pPointCol3.get_Point(1));
                                pBezierCurve.PutCoord(2, pPointCol3.get_Point(2));
                                pBezierCurve.PutCoord(3, pPointCol3.get_Point(3));

                                pNewSegmentCol.AddSegment((ISegment)pBezierCurve, ref a, ref b);
                            }
                        }//end for 遍历几何形体的每个节(片断)

                        CommonFunction.GeometryToArray(pNewSegmentCol as IGeometry, pArrayPoint);

                        IPolycurve2 pPolycurve2 = CommonFunction.BuildPolyLineFromSegmentCollection(pNewSegmentCol);

                        pGeometry = (IGeometry)pPolycurve2;

                        #endregion
                    }
                    if (pConvertGeometry.GeometryType == esriGeometryType.esriGeometryPolygon)//由线构成面
                    {
                        pGeometry = CommonFunction.PolylineToPolygon(pGeometry as IPolyline);
                    }
                    pGeometryArray.Add(pGeometry);
                }
                if (pGeometryArray.Count > 1)
                {
                    pConvertGeometry = pGeometryArray.get_Element(0) as IGeometry;
                    if (isRing == true)
                    {
                        for (int i = 1; i < pGeometryArray.Count; i++)
                        {
                            pConvertGeometry = CommonFunction.DiffenceGeometry(pConvertGeometry, pGeometryArray.get_Element(i) as IGeometry);
                        }
                    }
                    else
                    {
                        for (int i = 1; i < pGeometryArray.Count; i++)
                        {
                            pConvertGeometry = CommonFunction.UnionGeometry(pConvertGeometry, pGeometryArray.get_Element(i) as IGeometry);
                        }
                    }
                }
                else
                {
                    pConvertGeometry = pGeometryArray.get_Element(0) as IGeometry;
                }

                CommonFunction.AddZMValueForGeometry(ref pConvertGeometry, pArrayPoint);
            }
            else
            {
                PointCoordConvert(ref pConvertGeometry, A1, B1, C1, A2, B2, C2, A3, C3);
            }
        }
Example #39
0
        /// <summary>
        /// 获得缓冲区域内的点集合
        /// </summary>
        /// <param name="pBuff">缓冲区域</param>
        /// <returns>缓冲区域内的点集合(IPointCollection)</returns>
        private IPointCollection pntColl(IGeometry pBuff)
        {
            //=============================================================
            string pFld = m_Parameters[1].ToString().Trim();
            object o    = Type.Missing;

            IPointCollection pPointColl = new MultipointClass();
            ISpatialFilter   pFilter    = new SpatialFilterClass();
            //=============================================================
            ILayer        pLyr  = m_Parameters[0] as ILayer;
            IFeatureLayer pFLyr = pLyr as IFeatureLayer;

            if (pFLyr == null)
            {
                return(null);
            }

            IFeatureClass pFCls = pFLyr.FeatureClass;

            //=============================================================
            pFilter.Geometry      = pBuff;
            pFilter.GeometryField = pFCls.ShapeFieldName;
            pFilter.SpatialRel    = esriSpatialRelEnum.esriSpatialRelContains;

            IFeatureCursor pOutFeatureCursor = pFCls.Search(pFilter, false);

            IFeature pFeature = pOutFeatureCursor.NextFeature();

            while (pFeature != null)
            {
                IGeometry pGeometry = pFeature.Shape;
                if (pGeometry != null)
                {
                    if (pFld == "Z")
                    {
                        #region  中'Z'字段
                        if (pGeometry is IPoint)
                        {
                            IPoint pPnt = pGeometry as IPoint;
                            if (pPnt.Z > -999)
                            {
                                pPointColl.AddPoint(pPnt, ref o, ref o);
                            }
                        }
                        else
                        {
                            IPointCollection pPnts = pGeometry as IPointCollection;
                            for (int i = 0; i < pPnts.PointCount; i++)
                            {
                                IPoint pPnt = pPnts.get_Point(i);
                                if (pPnt.Z <= -999)
                                {
                                    //MessageBox.Show("无法读取该点数据!","提示");
                                    continue;
                                }
                                else
                                {
                                    pPointColl.AddPoint(pPnt, ref o, ref o);
                                }
                            }
                        }
                        #endregion
                    }
                    else
                    {
                        #region  中其他字段

                        if (pGeometry is IPoint)
                        {
                            IPoint pPnt = pGeometry as IPoint;
                            pPnt.Z = Convert.ToDouble(pFeature.get_Value(pFCls.Fields.FindField(pFld)).ToString().Trim());
                            if (pPnt.Z != -999)
                            {
                                pPointColl.AddPoint(pPnt, ref o, ref o);
                            }
                        }
                        else
                        {
                            IPointCollection pPnts = pGeometry as IPointCollection;
                            for (int i = 0; i < pPnts.PointCount; i++)
                            {
                                IPoint pPnt = pPnts.get_Point(i);
                                pPnt.Z = Convert.ToDouble(pFeature.get_Value(pFCls.Fields.FindField(pFld)).ToString().Trim());
                                if (pPnt.Z != -999)
                                {
                                    pPointColl.AddPoint(pPnt, ref o, ref o);
                                }
                            }
                        }
                        #endregion
                    }
                }
                pFeature = pOutFeatureCursor.NextFeature();
            }
            //0919
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pOutFeatureCursor);
            }
            catch (Exception ex)
            {
            }
            //0919

            return(pPointColl);
        }