public static void CreateFeature(IFeatureClass featureClass, IPoint point)
        {
            // Build the feature
            IFeature feature = featureClass.CreateFeature();
            feature.Shape = point;

            //Update a value on string field - name of the new feature (city)
            int fieldIndex = featureClass.FindField("AREANAME");
            feature.set_Value(fieldIndex, "Mentone");

            //Commit the new feature to the geodatabase
            feature.Store();
        }
Esempio n. 2
0
        public static void AddGeometryToFeatureClass(IGeometry geometry, IFeatureClass featureClass)
        {
            IWorkspaceEdit workspaceEdit = (featureClass as IDataset).Workspace as IWorkspaceEdit;
            workspaceEdit.StartEditing(true);
            workspaceEdit.StartEditOperation();

            IFeature feature = featureClass.CreateFeature();
            feature.Shape = geometry;
            feature.Store();

            workspaceEdit.StopEditOperation();
            workspaceEdit.StopEditing(true);
        }
Esempio n. 3
0
        /// <summary>
        /// 插入新记录-方法自身开始结束编辑,实体类和几何的数量和列表序号要一一对应
        /// </summary>
        /// <param name="FC">要素类</param>
        /// <param name="listModel">实体类属性表</param>
        /// <param name="listGeometry">要素几何</param>
        /// <param name="SaveCount">每次保存的入库行数</param>
        /// <returns>null为成功,其他为错误信息</returns>
        private string Insert(IFeatureClass FC, List<model> listModel, List<IGeometry> listGeometry, int SaveCount)
        {
            try
            {
                int count = listModel.Count;
                int count2 = listGeometry.Count;
                if (count == 0)
                    return "实体类为空";
                if (count != count2)
                    return "实体类和要素几何数目不同";

                IWorkspaceEdit WSE = (FC as IDataset).Workspace as IWorkspaceEdit;
                WSE.StartEditing(false);
                WSE.StartEditOperation();

                int flag = 0;

                for (int i = 0; i < count; i++)
                {
                    model model = listModel[i];

                    IFeature F = FC.CreateFeature();
                    if (listGeometry[i] != null)
                        F.Shape = listGeometry[i];

                    int index = -1;

                    #region 属性表赋值

                    index = FC.FindField("OBJECTID ");
                    if (index != -1)
                        F.set_Value(index, model.OBJECTID);

                    index = FC.FindField("YSJWJMC ");
                    if (index != -1)
                        F.set_Value(index, model.YSJWJMC);

                    index = FC.FindField("CPMC ");
                    if (index != -1)
                        F.set_Value(index, model.CPMC);

                    index = FC.FindField("TM ");
                    if (index != -1)
                        F.set_Value(index, model.TM);

                    index = FC.FindField("TH ");
                    if (index != -1)
                        F.set_Value(index, model.TH);

                    index = FC.FindField("MJ ");
                    if (index != -1)
                        F.set_Value(index, model.MJ);

                    index = FC.FindField("DMFBL ");
                    if (index != -1)
                        F.set_Value(index, model.DMFBL);

                    index = FC.FindField("SJL ");
                    if (index != -1)
                        F.set_Value(index, model.SJL);

                    index = FC.FindField("SJGS ");
                    if (index != -1)
                        F.set_Value(index, model.SJGS);

                    index = FC.FindField("CPSYQDWMC ");
                    if (index != -1)
                        F.set_Value(index, model.CPSYQDWMC);

                    index = FC.FindField("SJJKGLDWMC ");
                    if (index != -1)
                        F.set_Value(index, model.SJJKGLDWMC);

                    index = FC.FindField("CPSCDWMC ");
                    if (index != -1)
                        F.set_Value(index, model.CPSCDWMC);

                    index = FC.FindField("CPCBDWMC ");
                    if (index != -1)
                        F.set_Value(index, model.CPCBDWMC);

                    index = FC.FindField("CPSCRQ ");
                    if (index != -1)
                        F.set_Value(index, model.CPSCRQ);

                    index = FC.FindField("DXLB ");
                    if (index != -1)
                        F.set_Value(index, model.DXLB);

                    index = FC.FindField("XBJD ");
                    if (index != -1)
                        F.set_Value(index, model.XBJD);

                    index = FC.FindField("DBJD ");
                    if (index != -1)
                        F.set_Value(index, model.DBJD);

                    index = FC.FindField("BBWD ");
                    if (index != -1)
                        F.set_Value(index, model.BBWD);

                    index = FC.FindField("NBWD ");
                    if (index != -1)
                        F.set_Value(index, model.NBWD);

                    index = FC.FindField("DOMZSJXYZXXZB ");
                    if (index != -1)
                        F.set_Value(index, model.DOMZSJXYZXXZB);

                    index = FC.FindField("DOMZSJXYZXYZB ");
                    if (index != -1)
                        F.set_Value(index, model.DOMZSJXYZXYZB);

                    index = FC.FindField("DOMYXJXYZXXZB ");
                    if (index != -1)
                        F.set_Value(index, model.DOMYXJXYZXXZB);

                    index = FC.FindField("DOMYXJXYZXYZB ");
                    if (index != -1)
                        F.set_Value(index, model.DOMYXJXYZXYZB);

                    index = FC.FindField("TQCBJ ");
                    if (index != -1)
                        F.set_Value(index, model.TQCBJ);

                    index = FC.FindField("TQBL ");
                    if (index != -1)
                        F.set_Value(index, model.TQBL);

                    index = FC.FindField("SCYDDDJZ ");
                    if (index != -1)
                        F.set_Value(index, model.SCYDDDJZ);

                    index = FC.FindField("DTTYMC ");
                    if (index != -1)
                        F.set_Value(index, model.DTTYMC);

                    index = FC.FindField("ZYZWX ");
                    if (index != -1)
                        F.set_Value(index, model.ZYZWX);

                    index = FC.FindField("FDFS ");
                    if (index != -1)
                        F.set_Value(index, model.FDFS);

                    index = FC.FindField("GSKLGTYDH ");
                    if (index != -1)
                        F.set_Value(index, model.GSKLGTYDH);

                    index = FC.FindField("ZBDW ");
                    if (index != -1)
                        F.set_Value(index, model.ZBDW);

                    index = FC.FindField("GCXTMC ");
                    if (index != -1)
                        F.set_Value(index, model.GCXTMC);

                    index = FC.FindField("GCJZ ");
                    if (index != -1)
                        F.set_Value(index, model.GCJZ);

                    index = FC.FindField("XBJBQK ");
                    if (index != -1)
                        F.set_Value(index, model.XBJBQK);

                    index = FC.FindField("BBJBQK ");
                    if (index != -1)
                        F.set_Value(index, model.BBJBQK);

                    index = FC.FindField("DBJBQK ");
                    if (index != -1)
                        F.set_Value(index, model.DBJBQK);

                    index = FC.FindField("NBJBQK ");
                    if (index != -1)
                        F.set_Value(index, model.NBJBQK);

                    index = FC.FindField("HSBLCFM ");
                    if (index != -1)
                        F.set_Value(index, model.HSBLCFM);

                    index = FC.FindField("HSYXH ");
                    if (index != -1)
                        F.set_Value(index, model.HSYXH);

                    index = FC.FindField("HSYJJ ");
                    if (index != -1)
                        F.set_Value(index, model.HSYJJ);

                    index = FC.FindField("HSDW ");
                    if (index != -1)
                        F.set_Value(index, model.HSDW);

                    index = FC.FindField("SQDH ");
                    if (index != -1)
                        F.set_Value(index, model.SQDH);

                    index = FC.FindField("HSRQ ");
                    if (index != -1)
                        F.set_Value(index, model.HSRQ);

                    index = FC.FindField("YXSC ");
                    if (index != -1)
                        F.set_Value(index, model.YXSC);

                    index = FC.FindField("YXSMFBL ");
                    if (index != -1)
                        F.set_Value(index, model.YXSMFBL);

                    index = FC.FindField("SMHPFBL ");
                    if (index != -1)
                        F.set_Value(index, model.SMHPFBL);

                    index = FC.FindField("HSYXSJZLPJ ");
                    if (index != -1)
                        F.set_Value(index, model.HSYXSJZLPJ);

                    index = FC.FindField("KZZLLY ");
                    if (index != -1)
                        F.set_Value(index, model.KZZLLY);

                    index = FC.FindField("DEMGWJJ ");
                    if (index != -1)
                        F.set_Value(index, model.DEMGWJJ);

                    index = FC.FindField("SJSCFS ");
                    if (index != -1)
                        F.set_Value(index, model.SJSCFS);

                    index = FC.FindField("ZSJZRJ ");
                    if (index != -1)
                        F.set_Value(index, model.ZSJZRJ);

                    index = FC.FindField("ZCYFF ");
                    if (index != -1)
                        F.set_Value(index, model.ZCYFF);

                    index = FC.FindField("SCCLRJ ");
                    if (index != -1)
                        F.set_Value(index, model.SCCLRJ);

                    index = FC.FindField("SCCLQK ");
                    if (index != -1)
                        F.set_Value(index, model.SCCLQK);

                    index = FC.FindField("XSWS ");
                    if (index != -1)
                        F.set_Value(index, model.XSWS);

                    index = FC.FindField("SJZLZPJ ");
                    if (index != -1)
                        F.set_Value(index, model.SJZLZPJ);

                    index = FC.FindField("JBZLPJ ");
                    if (index != -1)
                        F.set_Value(index, model.JBZLPJ);

                    index = FC.FindField("CPJG ");
                    if (index != -1)
                        F.set_Value(index, model.CPJG);

                    index = FC.FindField("FFJZ ");
                    if (index != -1)
                        F.set_Value(index, model.FFJZ);

                    index = FC.FindField("FFDWMC ");
                    if (index != -1)
                        F.set_Value(index, model.FFDWMC);

                    index = FC.FindField("FFDWLXDH ");
                    if (index != -1)
                        F.set_Value(index, model.FFDWLXDH);

                    index = FC.FindField("FFDWCZ ");
                    if (index != -1)
                        F.set_Value(index, model.FFDWCZ);

                    index = FC.FindField("FFDWDZ ");
                    if (index != -1)
                        F.set_Value(index, model.FFDWDZ);

                    index = FC.FindField("FFDWYZBM ");
                    if (index != -1)
                        F.set_Value(index, model.FFDWYZBM);

                    index = FC.FindField("FFDWDZYX ");
                    if (index != -1)
                        F.set_Value(index, model.FFDWDZYX);

                    index = FC.FindField("FFDWWZ ");
                    if (index != -1)
                        F.set_Value(index, model.FFDWWZ);

                    index = FC.FindField("OID ");
                    if (index != -1)
                        F.set_Value(index, model.OID);

                    #endregion

                    F.Store();

                    flag++;
                    if (flag % SaveCount == 0)
                    {
                        flag = 0;
                        WSE.StopEditOperation();
                        WSE.StopEditing(true);

                        GC.Collect();
                        Thread.Sleep(500);

                        WSE.StartEditing(false);
                        WSE.StartEditOperation();
                    }
                }

                WSE.StopEditOperation();
                WSE.StopEditing(true);

                return null;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
Esempio n. 4
0
        //确定键
        private void buttonOK_Click(object sender, EventArgs e)
        {
            double dL = 0.0, dB = 0.0, dZJ = 0.0, dTransAngle = 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);          //震级
            bool   bTransAngle = double.TryParse(txtTransAngle.Text, out dTransAngle); //旋转角

            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, time);
            fwritePoint.WriteFeature(pFeaturePoint);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeaturePoint);
            //记录屏幕显示区域
            IEnvelope pEnvelope = null;

            //生成地震烈度椭圆
            //当都输入值的时候,生成椭圆
            if (bL && bB && bZJ && bTransAngle)
            {
                IGraphicsContainer graphicsContainer = _MainPageLayoutControl.ActiveView.FocusMap as IGraphicsContainer;
                string             sElementName      = "zjEllipticArc";
                DelectElementByName(graphicsContainer, sElementName);
                List <EllipticArcPro> pListEllipticArcPro = CalculatEllipticArc(pPoint, dZJ, dTransAngle);
                int tot    = pListEllipticArcPro.Count;
                int iCount = 1;
                foreach (EllipticArcPro pEllipticArcPro in pListEllipticArcPro)
                {
                    IEllipticArc pEll = new EllipticArcClass();
                    if (tot == 3)
                    {
                        pEll.PutCoordsByAngle(pEllipticArcPro.ellipseStd, pEllipticArcPro.CenterPoint, pEllipticArcPro.FromAngle, pEllipticArcPro.CentralAngle, pEllipticArcPro.rotationAngle, pEllipticArcPro.semiMajor / 100000, pEllipticArcPro.minorMajorRatio);
                    }
                    else
                    {
                        pEll.PutCoordsByAngle(pEllipticArcPro.ellipseStd, pEllipticArcPro.CenterPoint, pEllipticArcPro.FromAngle, pEllipticArcPro.CentralAngle, pEllipticArcPro.rotationAngle, pEllipticArcPro.semiMajor / 100000, pEllipticArcPro.minorMajorRatio);
                    }

                    IGeometry pGeo = EllipticArcTransPolygon(pEll);
                    pGeo.SpatialReference = spatialReference;
                    IPolygon pPloy = pGeo as IPolygon;
                    if (iCount == 1) //第一个烈度图层
                    {
                        IFeatureClass      pFeatureClass8LD = pFeatureLayer8LD.FeatureClass;
                        IFeatureClassWrite fwrite8LD        = pFeatureClass8LD as IFeatureClassWrite;
                        IFeature           pFeature8LD      = pFeatureClass8LD.CreateFeature();
                        pFeature8LD.Shape = pPloy;
                        fwrite8LD.WriteFeature(pFeature8LD);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeature8LD);
                        pFeature8LD = null;
                        if (dZJ > 5.3)
                        {
                            iCount++;
                        }
                        //更新显示区域
                        IActiveView pAV = _MainPageLayoutControl.ActiveView.FocusMap as IActiveView;
                        pEnvelope = pPloy.Envelope;
                        pEnvelope.Expand(1.8, 1.8, true);
                        pAV.Extent = pEnvelope;
                        pAV.Refresh();
                    }
                    else if (iCount == 2)
                    {
                        IFeatureClass      pFeatureClass7LD = pFeatureLayer7LD.FeatureClass;
                        IFeatureClassWrite fwrite7LD        = pFeatureClass7LD as IFeatureClassWrite;
                        IFeature           pFeature7LD      = pFeatureClass7LD.CreateFeature();
                        pFeature7LD.Shape = pPloy;
                        fwrite7LD.WriteFeature(pFeature7LD);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeature7LD);
                        pFeature7LD = null;
                        if (tot == 3)
                        {
                            iCount++;
                        }
                    }
                    else if (iCount == 3)
                    {
                        IFeatureClass      pFeatureClass6LD = pFeatureLayer6LD.FeatureClass;
                        IFeatureClassWrite fwrite6LD        = pFeatureClass6LD as IFeatureClassWrite;
                        IFeature           pFeature6LD      = pFeatureClass6LD.CreateFeature();
                        pFeature6LD.Shape = pPloy;
                        fwrite6LD.WriteFeature(pFeature6LD);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeature6LD);
                        pFeature6LD = null;
                        iCount++;
                    }
                }
            }
            pFeaturePoint = null;
            pWorkspaceEdit.StopEditOperation();
            pWorkspaceEdit.StopEditing(true);
            this.Hide();
            setFormIPoint(pPoint, textBoxLevel.Text, pEnvelope);
            //修改标题
            IElement     pElementTitle     = _MainPageLayoutControl.FindElementByName("Title");
            ITextElement pTextElementTitle = pElementTitle as ITextElement;
            string       sXZQName          = GetXZQName(pPoint);
            string       sText             = sXZQName + "M" + textBoxLevel.Text + "级地震震区水库分布图";

            pTextElementTitle.Text = sText;

            MessageBox.Show("操作成功!", "提示");
        }
Esempio n. 5
0
        /// <summary>
        /// 创建面实体
        /// </summary>
        /// <param name="pITable">数据表对象</param>
        /// <param name="entinyNode">VCT空间实体节点</param>
        public override void CreateFeature(ITable pITable, EntityNode entinyNode)
        {
            PolygonNode pPolygonNode = entinyNode as PolygonNode;
            if (pPolygonNode != null)
            {
                IFeatureClass pFeatureCls = pITable as IFeatureClass;
                this.Feature = pFeatureCls.CreateFeature();

                ///标识码赋值
                int dBSMIndex = -1;
                dBSMIndex = this.Feature.Fields.FindField(m_strEntityIDFiled);
                if (dBSMIndex != -1)
                    this.Feature.set_Value(dBSMIndex, pPolygonNode.EntityID);

                ///要素代码赋值
                int dSYDMIndex = -1;
                dSYDMIndex = this.Feature.Fields.FindField(m_strYSDMField);
                if (dSYDMIndex != -1)
                    this.Feature.set_Value(dSYDMIndex, pPolygonNode.FeatureCode);


                //根据面特征类型构面 
                bool bGetGeometry = false;///指示是否获取图形数据

                ///从配置表获取面的类型InDireCoordinatePolygon表示间接坐标构面
                if (Metadata.MetaDataFile.GraphConfig.GetGraphMark("POLYGONFEATURETYPE", pPolygonNode.PolygonType.ToString()) == "InDireCoordinatePolygon")
                {
                    IGeometryCollection pGeoCollection = new PolygonClass();
                    IPointCollection pPtCollection = new RingClass();

                    ///采用间接构面的方式LineStructPolygon表示引用线构面
                    if (Metadata.MetaDataFile.GraphConfig.GetGraphMark("POLYGONTYPE", pPolygonNode.ComposeType.ToString()) == "LineStructPolygon")
                    {
                        for (int i = 0; i < pPolygonNode.LineNodes.Count; i++)
                        {
                            LineNodeEx pLineNodeEx = pPolygonNode.LineNodes[i];
                            if (pLineNodeEx == null)
                                continue;
                           
                            ///标识码为0表示对象分割标识
                            if (pLineNodeEx.EntityID != 0)
                            {
                                IPoint pPrePoint=null;
                                if (pPtCollection.PointCount > 0)
                                    pPrePoint = pPtCollection.get_Point(pPtCollection.PointCount-1);
                                IPointCollection pPointCollection=GetPointCollection(pLineNodeEx, pPrePoint);
                                if (pPointCollection != null)
                                    pPtCollection.AddPointCollection(pPointCollection);
                                if (i == pPolygonNode.LineNodes.Count - 1)
                                {
                                    IRing pRing = pPtCollection as IRing;
                                    pRing.Close();///闭合当前环
                                    object oTypeMissing = Type.Missing;
                                    pGeoCollection.AddGeometry(pRing as IGeometry, ref oTypeMissing, ref oTypeMissing);
                                    bGetGeometry = true;
                                    pPtCollection = new RingClass();///清空点集数据
                                }
                            }
                            else///独到标识码为0时闭合图形
                            {
                                IRing pRing = pPtCollection as IRing;
                                pRing.Close();///闭合当前环
                                object oTypeMissing = Type.Missing;
                                pGeoCollection.AddGeometry(pRing as IGeometry, ref oTypeMissing, ref oTypeMissing);
                                bGetGeometry = true;
                                pPtCollection = new RingClass();///清空点集数据
                            }
                        }
                        if (bGetGeometry)
                        {
                            (this.Feature as IFeature).Shape = pGeoCollection as IGeometry;
                        }
                    }
                }
                else if (pPolygonNode.PolygonType == 1)
                {

                }


                this.Feature.Store();
            }
        }
Esempio n. 6
0
        /// <summary>
        /// 根据点集坐标绘制线要素
        /// </summary>
        /// <param name="featureLayer"></param>
        /// <param name="lstPoint"></param>
        public void CreateLine(IFeatureLayer featureLayer, List <IPoint> lstPoint, int ID)
        {
            //try
            //{
            IFeatureClass featureClass = featureLayer.FeatureClass;

            if (featureClass.ShapeType == esriGeometryType.esriGeometryPolyline)
            {
                IPointCollection multipoint = new MultipointClass();
                if (lstPoint.Count < 2)
                {
                    MessageBox.Show(@"请选择两个及两个以上点数。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                ISegmentCollection pPath = new PathClass();
                ILine    pLine;
                ISegment pSegment;
                object   o = Type.Missing;
                for (int i = 0; i < lstPoint.Count - 1; i++)
                {
                    pLine = new LineClass();
                    pLine.PutCoords(lstPoint[i], lstPoint[i + 1]);
                    pSegment = pLine as ISegment;
                    pPath.AddSegment(pSegment, ref o, ref o);
                }
                IGeometryCollection pPolyline = new PolylineClass();
                pPolyline.AddGeometry(pPath as IGeometry, ref o, ref o);

                IDataset       dataset       = (IDataset)featureClass;
                IWorkspace     workspace     = dataset.Workspace;
                IWorkspaceEdit workspaceEdit = workspace as IWorkspaceEdit;

                workspaceEdit.StartEditing(true);
                workspaceEdit.StartEditOperation();

                IFeature feature = featureClass.CreateFeature();

                IGeometry geometry = pPolyline as IGeometry;
                DrawCommon.HandleZMValue(feature, geometry);//几何图形Z值处理

                feature.Shape = pPolyline as PolylineClass;
                int iFieldID = feature.Fields.FindField(GIS_Const.FIELD_BID);
                feature.Value[iFieldID] = ID.ToString();
                feature.Store();
                workspaceEdit.StopEditOperation();
                workspaceEdit.StopEditing(false);

                IEnvelope envelop = feature.Shape.Envelope;
                DataEditCommon.g_pMyMapCtrl.ActiveView.Extent = envelop;
                DataEditCommon.g_pMyMapCtrl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewBackground, null, null);
            }
            else
            {
                MessageBox.Show(@"请选择线图层。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            //}
            //catch
            //{
            //    return;
            //}
        }
Esempio n. 7
0
        public static IFeature CutOffPolylineByPoint(IFeatureClass featureClass, IFeature polylineFeature,
                                                     IFeature pointFeature, string keyValue, string sKeyValue, string eKeyValue)
        {
            int idxKeyField  = pointFeature.Fields.FindField(keyValue);
            int idxSKeyField = polylineFeature.Fields.FindField(sKeyValue);
            int idxEKeyField = polylineFeature.Fields.FindField(eKeyValue);

            if (idxKeyField == -1 || idxSKeyField == -1 || idxEKeyField == -1)
            {
                return(null);
            }
            bool   hasZ  = FeatureClassUtil.CheckHasZ(featureClass);
            bool   hasM  = FeatureClassUtil.CheckHasM(featureClass);
            IPoint point = pointFeature.Shape as IPoint;

            if (point == null)
            {
                return(null);
            }
            IPolyline polyline1 = polylineFeature.ShapeCopy as IPolyline;

            if (polyline1 == null)
            {
                return(null);
            }
            IPolyline firstPolyline = new PolylineClass
            {
                FromPoint = GeometryHelper.CreatePoint(polyline1.FromPoint.X, polyline1.FromPoint.Y, polyline1.FromPoint.Z, polyline1.FromPoint.M, hasZ, hasM),
                ToPoint   = GeometryHelper.CreatePoint(point.X, point.Y, point.Z, point.M, hasZ, hasM)
            };

            if (hasZ)
            {
                IZAware pZAware = firstPolyline as IZAware;
                pZAware.ZAware = true;
            }
            if (hasM)
            {
                IMAware pMAware = firstPolyline as IMAware;
                pMAware.MAware = true;
            }
            polylineFeature.Shape = firstPolyline;
            polylineFeature.Store();
            IFeature  secondFeature  = featureClass.CreateFeature();
            IPolyline secondPolyline = new PolylineClass
            {
                FromPoint = GeometryHelper.CreatePoint(point.X, point.Y, point.Z, point.M, hasZ, hasM),
                ToPoint   = GeometryHelper.CreatePoint(polyline1.ToPoint.X, polyline1.ToPoint.Y, polyline1.ToPoint.Z, polyline1.ToPoint.M, hasZ, hasM),
            };

            if (hasZ)
            {
                IZAware pZAware = secondPolyline as IZAware;
                pZAware.ZAware = true;
            }
            if (hasM)
            {
                IMAware pMAware = secondPolyline as IMAware;
                pMAware.MAware = true;
            }
            secondFeature.Shape = secondPolyline;
            IField pField;

            for (int i = 0; i < featureClass.Fields.FieldCount; i++)
            {
                pField = featureClass.Fields.Field[i];
                if (pField.Type == esriFieldType.esriFieldTypeGeometry)
                {
                    continue;
                }
                int idx = secondFeature.Fields.FindField(pField.Name);
                if (pField.Editable && idx != -1)
                {
                    secondFeature.Value[idx] = polylineFeature.Value[idx];
                }
            }
            secondFeature.Store();

            polylineFeature.Value[idxEKeyField] = pointFeature.Value[idxKeyField];
            polylineFeature.Store();
            secondFeature.Value[idxSKeyField] = pointFeature.Value[idxKeyField];
            secondFeature.Store();
            return(secondFeature);
        }
 /// <summary>
 /// ���ݼ���ͼ�������Ҫ��
 /// </summary>
 /// <params name="featureLayer">��ǰ�༭ͼ��</params>
 /// <params name="geom">Ҫ�ؼ���</params>
 public static void CreateFeatureNoEditor(IFeatureClass featureClass, IGeometry geometry, List<ziduan> list)
 {
     IFeature feature = featureClass.CreateFeature();
     DataEditCommon.ZMValue(feature, geometry);     //����ͼ��Zֵ����
     feature.Shape = geometry;
     if (list != null)
     {
         for (int j = 0; j < list.Count; j++)
         {
             if (feature.Fields.FindField(list[j].name) > 0)
             {
                 feature.set_Value(feature.Fields.FindField(list[j].name), list[j].value);
             }
         }
     }
     feature.Store();
 }
Esempio n. 9
0
        private void InsertTransaction(IJTXTransaction2 trans, Dictionary <esriGeometryType, IFeatureClass> fcs)
        {
            // Currently does not do anythign with the annotation elements

            // Add and Delete transactions will only have a single geometry
            // But Modify transactions will have a before and an After geometry
            for (int i = 0; i < trans.Geometry.GeometryCount; i++)
            {
                IGeometry     geom = trans.Geometry.get_Geometry(i);
                IFeatureClass fc   = fcs[geom.GeometryType];
                IFeature      feat = fc.CreateFeature();

                // Figure out the more detailed transaction type for modified (Before or After feature)
                jtxTransactionType transType = trans.TransactionType;
                if (transType == jtxTransactionType.jtxTransactionTypeModify)
                {
                    if (i == 0) // The first item is the before
                    {
                        transType = jtxTransactionType.jtxTransactionTypeModify | jtxTransactionType.jtxTransactionTypeDelete;
                    }
                    else // There should only be 2 items
                    {
                        transType = jtxTransactionType.jtxTransactionTypeModify | jtxTransactionType.jtxTransactionTypeAdd;
                    }
                }

                // Set the basic values
                feat.set_Value(idIdx, trans.GFID);
                feat.set_Value(idFieldIdx, trans.GFIDField);
                feat.set_Value(jobIdIdx, trans.JobID);
                feat.set_Value(loggedByIdx, trans.LoggedBy);
                feat.set_Value(tabNameIdx, trans.TableName);
                feat.set_Value(transTypeIdx, transType);
                feat.set_Value(transDateIdx, trans.TransactionDate);
                feat.set_Value(sessionIdIdx, trans.SessionID);

                IJTXTransactionAttributeSet attribs = trans.Attributes;

                // Convert the attributes to a basic XML fragment
                // This will be of the form:
                // <Attributes>
                //   <Attribute>
                //     <FieldName>Field1</FieldName>
                //     <Value>SomeValue</Value>
                //   </Attribute>
                //   ...
                // </Attributes>
                XElement attribsXML = new XElement("Attributes");
                for (int j = 0; j < attribs.Count; j++)
                {
                    IJTXTransactionAttribute attribute = attribs.get_Item(j);
                    string val;
                    // Attributes also have before and after values. Based on the transaction type, see if we need the before or after value
                    if ((transType & jtxTransactionType.jtxTransactionTypeDelete) != 0)
                    {
                        val = attribute.PreviousValue;
                    }
                    else
                    {
                        val = attribute.NewValue;
                    }

                    attribsXML.Add(
                        new XElement("Attribute",
                                     new XElement("FieldName", attribute.FieldName),
                                     new XElement("Value", val)
                                     ));
                }
                string attribString = attribsXML.ToString(SaveOptions.DisableFormatting);
                feat.set_Value(attributesIdx, attribString == null ? DBNull.Value : (object)attribString);

                // Set the spatial reference of the geometry
                var sourceSR = GetSpatialReference(trans.TableName);
                geom.SpatialReference = sourceSR;
                var targetSR = ((IGeoDataset)fc).SpatialReference;
                if (sourceSR != null && targetSR != null && sourceSR.Name != targetSR.Name)
                {
                    geom.Project(targetSR); // Project to the right SR
                }
                feat.Shape = geom;

                feat.Store();
            }
        }
Esempio n. 10
0
        private void buttonX_ok_Click(object sender, EventArgs e)
        {
            //add all point
            List <IPoint> pointList = new List <IPoint>();

            Microsoft.Office.Interop.Excel.Application myExcel = new Microsoft.Office.Interop.Excel.Application();
            object missing = System.Reflection.Missing.Value;

            myExcel.Application.Workbooks.Open(textBoxX1.Text, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); //this.txtFile.Text为Excel文件的全路径
            Microsoft.Office.Interop.Excel.Workbook myBook = myExcel.Workbooks[1];

            //获取第一个Sheet
            Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)myBook.Sheets[1];
            string sheetName = sheet.Name; //Sheet名

            myBook.Close(Type.Missing, Type.Missing, Type.Missing);
            myExcel.Quit();

            //read excel file to creat Field
            string          strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + this.textBoxX1.Text + ";Extended Properties=Excel 8.0";
            OleDbConnection conn   = new OleDbConnection(strCon);
            string          sql1   = string.Format("select * from [{0}$]", sheetName);

            conn.Open();

            OleDbDataAdapter myCommand = new OleDbDataAdapter(sql1, strCon);
            DataSet          ds        = new DataSet();

            myCommand.Fill(ds);
            conn.Close();

            int xIndex = 0;
            int yIndex = 0;
            int zIndex = 0;

            for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
            {
                if (ds.Tables[0].Columns[i].ColumnName == "X_经度")
                {
                    xIndex = i;
                }
                if (ds.Tables[0].Columns[i].ColumnName == "Y_纬度")
                {
                    yIndex = i;
                }
                if (ds.Tables[0].Columns[i].ColumnName.Contains("Z_高程"))
                {
                    zIndex = i;
                }
            }

            ISpatialReference pSpaReference = new UnknownCoordinateSystemClass();

            pSpaReference.SetDomain(-8000000, 8000000, -800000, 8000000);
            IFeatureClass pFt = CreateShapeFile(ds, this.textBoxX2.Text, pSpaReference);

            if (pFt == null)
            {
                return;
            }
            else
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    //根据XY坐标添加点,edit attribute
                    IsNumberic isNum = new IsNumberic();
                    ESRI.ArcGIS.Geometry.IPoint pPoint = new ESRI.ArcGIS.Geometry.PointClass();
                    if (ds.Tables[0].Rows[i][xIndex].ToString() == "" || ds.Tables[0].Rows[i][xIndex].ToString() == " ")
                    {
                        break;
                    }
                    if (isNum.IsNumber(ds.Tables[0].Rows[i][xIndex].ToString()) && isNum.IsNumber(ds.Tables[0].Rows[i][yIndex].ToString()))
                    {
                        pPoint.X = System.Convert.ToSingle(ds.Tables[0].Rows[i][xIndex].ToString());
                        pPoint.Y = System.Convert.ToSingle(ds.Tables[0].Rows[i][yIndex].ToString());
                        pPoint.Z = System.Convert.ToSingle(ds.Tables[0].Rows[i][zIndex].ToString());
                        IFeature pFeature = pFt.CreateFeature();
                        pFeature.Shape = pPoint;

                        pFeature.Store();
                        for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                        {
                            if (ds.Tables[0].Columns[j].ColumnName.Contains("里程"))
                            {
                                continue;
                            }
                            //pFeature.set_Value(pFeature.Fields.FindField(ds.Tables[0].Columns[j].ColumnName), ds.Tables[0].Rows[i][j]);
                            pFeature.set_Value(j + 2, ds.Tables[0].Rows[i][j].ToString());
                        }
                        pFeature.Store();

                        pointList.Add(pPoint);
                    }
                    else
                    {
                        MessageBox.Show("the" + i + "rows x and y value is unvalid!");
                    }
                }
            }

            ClsGDBDataCommon processDataCommon = new ClsGDBDataCommon();
            string           strInputPath      = System.IO.Path.GetDirectoryName(textBoxX2.Text);
            string           strInputName      = System.IO.Path.GetFileName(textBoxX2.Text);

            IFeatureLayer pFeatureLayer = new FeatureLayerClass();

            pFeatureLayer.FeatureClass = pFt;
            pFeatureLayer.Name         = System.IO.Path.GetFileNameWithoutExtension(System.IO.Path.GetFileNameWithoutExtension(strInputName));


            //create line shape file
            IPointCollection PointCollection = ReadPoint(pFeatureLayer);
            string           lineName        = strInputPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(strInputName) + "_line.shp";

            CreateLineShpFile(lineName, pSpaReference);
            //将所有的点连接成线
            List <IPolyline> Polyline       = CreatePolyline(PointCollection);
            List <double>    lineLengthList = new List <double>();
            //将连接成的线添加到线图层中
            string pLineFile = lineName;
            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 plineLayer = new FeatureLayerClass();

            plineLayer.FeatureClass = pWS.OpenFeatureClass(pFileName);
            AddFeature(plineLayer, Polyline, pointList, lineLengthList);
            plineLayer.Name = pFeatureLayer.Name + "_line";

            m_pMapCtl.AddLayer(plineLayer as ILayer, 0);
            m_pMapCtl.AddLayer(pFeatureLayer as ILayer, 0);
            m_pMapCtl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);

            ImpSymbolFromFile(textBoxX3.Text, pFeatureLayer, plineLayer);

            this.Close();
        }
        /*
         * A function to populate a referenced FeatureClass (fc) with the contents of a Google Maps Engine map
         */
        public void populateFCWithGoogleMapsEngineMap(ref IFeatureClass fc, ref MapsEngine.DataModel.gme.Map map)
        {
            // create a feature object
            log.Debug("Creating a new Feature object to be used later in populating the FC.");
            IFeature feature = fc.CreateFeature();

            log.Debug("Creating feature for map " + map.id);

            // create a projectId value from the MapId
            String projectId = map.id.Split("-".ToCharArray())[0];

            // Update the values for this feature
            feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_CustomerId_Name), projectId);
            log.Debug(Properties.Resources.GeodatabaseUtilities_schema_CustomerId_Name + ": " + projectId);
            feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_AssetId_Name), map.id);
            log.Debug(Properties.Resources.GeodatabaseUtilities_schema_AssetId_Name + ": " + map.id);
            feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_MapAssetId_Name), map.id);
            log.Debug(Properties.Resources.GeodatabaseUtilities_schema_MapAssetId_Name + ": " + map.id);
            feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_AssetType_Name), "map");
            log.Debug(Properties.Resources.GeodatabaseUtilities_schema_AssetType_Name + ": " + "map");
            feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_AssetName_Name), map.name);
            log.Debug(Properties.Resources.GeodatabaseUtilities_schema_AssetName_Name + ": " + map.name);
            feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_ParentAssetId_Name), projectId);
            log.Debug(Properties.Resources.GeodatabaseUtilities_schema_ParentAssetId_Name + ": " + projectId);

            // attempt to set the description
            try
            {
                // attempt to set the feature description (truncating if necessary)
                feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_AssetDescription_Name)
                    , map.description.Length > 256
                    ? map.description.Substring(0, 252) + "..."
                    : map.description);
                log.Debug(Properties.Resources.GeodatabaseUtilities_schema_AssetDescription_Name + ": " + map.description);
            }
            catch (System.Exception ex)
            {
                // warn
                log.Warn(ex);
            }

            // check to see if the bbox object is not null
            log.Debug("Adding spatial representation if available.");
            if (map.bbox != null && map.bbox.Count() == 4)
            {
                // deterine the maximum and minimum bounds of all layers within this map
                // 0=West, 1=South, 2=East, 3=North
                double XMAX = map.bbox[2];
                log.Debug("XMAX: " + XMAX);
                double YMAX = map.bbox[3];
                log.Debug("YMAX: " + YMAX);
                double XMIN = map.bbox[0];
                log.Debug("XMIN: " + XMIN);
                double YMIN = map.bbox[1];
                log.Debug("YMIN: " + YMIN);


                // determine the map extent based on the layers maximum extent
                IPoint pExtentNE = new Point();
                pExtentNE.X = XMAX;
                pExtentNE.Y = YMAX;
                IPoint pExtentSW = new Point();
                pExtentSW.X = XMIN;
                pExtentSW.Y = YMIN;
                IPoint pExtentNW = new Point();
                pExtentNW.X = XMIN;
                pExtentNW.Y = YMAX;
                IPoint pExtentSE = new Point();
                pExtentSE.X = XMAX;
                pExtentSE.Y = YMIN;

                // define the polygon bounding box (NE/SW) as a point collection
                log.Debug("Building polygon object.");
                IPointCollection pExtentPointCol = new Polygon();
                pExtentPointCol.AddPoint(pExtentNE, Type.Missing, Type.Missing);
                pExtentPointCol.AddPoint(pExtentSE, Type.Missing, Type.Missing);
                pExtentPointCol.AddPoint(pExtentSW, Type.Missing, Type.Missing);
                pExtentPointCol.AddPoint(pExtentNW, Type.Missing, Type.Missing);

                // create a polygon, p, from the point collection, then close the polygon
                IPolygon pExtent = (IPolygon)pExtentPointCol;
                pExtent.Close();

                // add the polygon, p, as the new feature's geometry
                if (pExtent != null)
                {
                    log.Debug("Setting feature's geometry.");
                    feature.Shape = pExtent;
                }
                else
                {
                    log.Warn("Polygon is not valid, setting feature geometry to default worldwide.");
                    feature.Shape = worldPolygon;
                }
            }
            else
            {
                // no spatial information contained, use world
                log.Warn("No spatial representation, setting feature geometry to default worldwide.");
                //feature.Shape = worldPolygon;
            }

            // Commit the new feature to fc
            log.Debug("Storing feature.");
            feature.Store();

            // add all child layers within this map
            log.Debug("Verifying the map has layers.");
            if (map.layers != null)
            {
                // go through each layer in the map
                log.Debug("Going through each layer in the map.");
                foreach (MapsEngine.DataModel.gme.MapLayer layer in map.layers)
                {
                    // populate the features in the layer
                    log.Debug("Processing layer " + layer.id);
                    populateFCWithGoogleMapsEngineLayer(ref fc, map.id, map.id, layer);
                }
            }

            // Verifying the map has a folders object
            log.Debug("Verifying the map has a folders object.");
            if (map.folders != null && map.folders.Count() > 0)
            {
                // populate the features in the folder
                log.Debug("Processing folders");
                populateFCWithGoogleMapsEngineFolders(ref fc, map.id, map.id, map.folders);
            }
        }
        /*
         * A function to populate a referenced Feature Class (fc) with the contents of a Google Mpas Engine map folder
         */
        protected void populateFCWithGoogleMapsEngineFolders(ref IFeatureClass fc, string mapId, string parentId, List<MapsEngine.DataModel.gme.MapFolder> folders)
        {
            // establish a feature object
            IFeature feature;

            // add all child folder within this map
            for (int f = 0; f < folders.Count(); f++)
            {
                // grap the current folder
                MapsEngine.DataModel.gme.MapFolder folder = folders[f];

                // add all child layers within this map
                foreach (MapsEngine.DataModel.gme.MapLayer layer in folder.layers)
                {
                    populateFCWithGoogleMapsEngineLayer(ref fc, mapId, "Folder" + f, layer);
                }

                // create a new feature
                feature = fc.CreateFeature();

                // Update the values for this feature
                feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_CustomerId_Name), mapId.Split("-".ToCharArray())[0]);
                feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_AssetId_Name), "Folder" + f);
                feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_MapAssetId_Name), mapId);
                feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_AssetType_Name), "folder");
                feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_AssetName_Name), "Folder " + f);
                feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_ParentAssetId_Name), parentId);

                // Commit the new feature to fc
                feature.Store();

                // if the folder contains subfolders, add them
                if (folder.folders != null && folder.folders.Count() > 0)
                {
                    populateFCWithGoogleMapsEngineFolders(ref fc, mapId, "Folder" + f, folder.folders);
                }
            }
        }
        /*
         * A function to populate a referenced Feature Class (fc) with the contents of a Google Maps Engine map layer
         */
        protected void populateFCWithGoogleMapsEngineLayer(ref IFeatureClass fc, string mapId, string parentId, MapsEngine.DataModel.gme.MapLayer layer)
        {
            // create a new feature
            IFeature feature;

            log.Debug("Creating a feature for layer " + layer.id);

            // attempt to process the assets within a the layer
            try
            {
                // fetch the layer asset object from the API
                log.Debug("Fetching an asset object for the layer.");
                MapsEngine.DataModel.gme.Asset layerAsset = api.getAssetById(ext.getToken(), layer.id);

                // create a new feature
                log.Debug("Creating a new feature.");
                feature = fc.CreateFeature();

                // Update the values for this feature
                feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_CustomerId_Name), mapId.Split("-".ToCharArray())[0]);
                log.Debug(Properties.Resources.GeodatabaseUtilities_schema_CustomerId_Name + ": " + mapId.Split("-".ToCharArray())[0]);
                feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_AssetId_Name), layer.id);
                log.Debug(Properties.Resources.GeodatabaseUtilities_schema_AssetId_Name + ": " + layer.id);
                feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_MapAssetId_Name), mapId);
                log.Debug(Properties.Resources.GeodatabaseUtilities_schema_MapAssetId_Name + ": " + mapId);
                feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_AssetType_Name), layerAsset.type);
                log.Debug(Properties.Resources.GeodatabaseUtilities_schema_AssetType_Name + ": " + layerAsset.type);
                feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_AssetName_Name), layerAsset.name);
                log.Debug(Properties.Resources.GeodatabaseUtilities_schema_AssetName_Name + ": " + layerAsset.name);
                feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_ParentAssetId_Name), parentId);
                log.Debug(Properties.Resources.GeodatabaseUtilities_schema_ParentAssetId_Name + ": " + parentId);

                // attempt to set the description object
                try
                {
                    // set the layer description value (truncate if necessary)
                    feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_AssetDescription_Name)
                        , layerAsset.description.Length > 256
                        ? layerAsset.description.Substring(0, 252) + "..."
                        : layerAsset.description);
                    log.Debug(Properties.Resources.GeodatabaseUtilities_schema_AssetDescription_Name + ": " + layerAsset.description);
                }
                catch (System.Exception ex)
                {
                    // log warning
                    log.Warn(ex);
                }

                // verify the layer has a bbox and has two valid points
                if (layerAsset.bbox != null && layerAsset.bbox.Count() == 4)
                {
                    // deterine the maximum and minimum bounds of all layers within this map
                    // 0=West, 1=South, 2=East, 3=North
                    double XMAX = layerAsset.bbox[2];
                    log.Debug("XMAX: " + XMAX);
                    double YMAX = layerAsset.bbox[3];
                    log.Debug("YMAX: " + YMAX);
                    double XMIN = layerAsset.bbox[0];
                    log.Debug("XMIN: " + XMIN);
                    double YMIN = layerAsset.bbox[1];
                    log.Debug("YMIN: " + YMIN);

                    // determine the map extent based on the layers maximum extent
                    IPoint pExtentNE = new Point();
                    pExtentNE.X = XMAX;
                    pExtentNE.Y = YMAX;
                    IPoint pExtentSW = new Point();
                    pExtentSW.X = XMIN;
                    pExtentSW.Y = YMIN;
                    IPoint pExtentNW = new Point();
                    pExtentNW.X = XMIN;
                    pExtentNW.Y = YMAX;
                    IPoint pExtentSE = new Point();
                    pExtentSE.X = XMAX;
                    pExtentSE.Y = YMIN;

                    // define the polygon bounding box (NE/SW) as a point collection
                    IPointCollection pExtentPointCol = new Polygon();
                    pExtentPointCol.AddPoint(pExtentNE, Type.Missing, Type.Missing);
                    pExtentPointCol.AddPoint(pExtentSE, Type.Missing, Type.Missing);
                    pExtentPointCol.AddPoint(pExtentSW, Type.Missing, Type.Missing);
                    pExtentPointCol.AddPoint(pExtentNW, Type.Missing, Type.Missing);

                    // create a polygon, p, from the point collection, then close the polygon
                    IPolygon pExtent = (IPolygon)pExtentPointCol;
                    pExtent.Close();

                    // add the polygon, p, as the new feature's geometry
                    if (pExtent != null)
                    {
                        // set the shape geometry
                        log.Debug("Setting the feature's geometry as the polygon.");
                        feature.Shape = pExtent;
                    }
                    else
                    {
                        // set the feature's goemetry as the default world
                        log.Debug("Invalid spatial representation, setting feature goemtry as the world.");
                        feature.Shape = worldPolygon;
                    }
                }
                else
                {
                    // the layer does not have spatial information
                    log.Warn("Layer has no bbox information");
                    //feature.Shape = worldPolygon;
                }

                // Commit the new feature to fc
                log.Debug("Storing feature.");
                feature.Store();
            }
            catch (Exception ex)
            {
                // log the warning
                log.Warn(ex);
            }
        }
Esempio n. 14
0
 object ICopyFeatures.CopyFromMdb(IFeature copiedFeature, IFeatureClass toFeatureClass)
 {
     MessageBox.Show(string.Format("line 492 DataManager \n{0}", copiedFeature.get_Value(2)));
        IFeature newfeature = toFeatureClass.CreateFeature();
        var simplifiedFeature = newfeature as IFeatureSimplify;
        IGeometry myGeometry = copiedFeature.ShapeCopy;
        try
        {
        simplifiedFeature.SimplifyGeometry(myGeometry);
        newfeature.Shape = myGeometry;
        newfeature.Store();
        }
        catch (Exception e1) { MessageBox.Show(string.Format("line 501 DataManager \n{0}", e1)); }
        //MessageBox.Show(string.Format("line 503 DataManager \n{0}", newfeature.OID));
        //return newfeature.OID;
        return 1;
 }
Esempio n. 15
0
        public static void updateAcetate(SEE see, IFeatureClass featureClass, ISDUTExtension ext)
        {
            if(see == null)
            {
                return;
            }

            Logger.Write("Update acetate");
            IFeature feat = null;
            if(featureClass.FeatureCount(null) < 1)
            {
                feat = featureClass.CreateFeature();
                feat.Shape = see.Shape;
                feat.Store();
            }
            else
            {
                feat = featureClass.Update(null,false).NextFeature();
                feat.Shape = see.Shape;
                feat.Store();
            }
            Logger.Write("Update acetate -- Refresh");

            ((IActiveView)ext.FocusMap).Refresh();
        }
        private void NodeToFeatureClass(osm osmDocument, IFeatureClass pointFeatureClass)
        {
            // initial safety check -- consider throwing an exception instead
            if (osmDocument == null)
            {
                return;
            }

            if (osmDocument.Items == null)
            {
                return;
            }

            if (pointFeatureClass == null)
            {
                return;
            }

            //
            int tagCollectionPointFieldIndex = pointFeatureClass.FindField("osmTags");
            int osmUserPointFieldIndex = pointFeatureClass.FindField("osmuser");
            int osmUIDPointFieldIndex = pointFeatureClass.FindField("osmuid");
            int osmVisiblePointFieldIndex = pointFeatureClass.FindField("osmvisible");
            int osmVersionPointFieldIndex = pointFeatureClass.FindField("osmversion");
            int osmChangesetPointFieldIndex = pointFeatureClass.FindField("osmchangeset");
            int osmTimeStampPointFieldIndex = pointFeatureClass.FindField("osmtimestamp");
            int osmIDPointFieldIndex = pointFeatureClass.FindField("OSMID");

            ISpatialReferenceFactory srFactory = new SpatialReferenceEnvironmentClass();
            ISpatialReference wgs84 = srFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984) as ISpatialReference;

            foreach (var documentItem in osmDocument.Items)
            {
                if (documentItem is node)
                {
                   // if (DoesHaveKeys(documentItem))
                   // {
                        node currentNode = documentItem as node;

                        IFeature newPointFeature = pointFeatureClass.CreateFeature();

                        IPoint pointGeometry = new PointClass();
                        pointGeometry.X = Convert.ToDouble(currentNode.lon, new CultureInfo("en-US"));
                        pointGeometry.Y = Convert.ToDouble(currentNode.lat, new CultureInfo("en-US"));
                        pointGeometry.SpatialReference = wgs84;

                        newPointFeature.Shape = pointGeometry;

                        if (osmUserPointFieldIndex != -1)
                        {
                        newPointFeature.set_Value(osmUserPointFieldIndex, currentNode.user);
                        }
                        if (osmUIDPointFieldIndex != -1)
                        {
                            newPointFeature.set_Value(osmUIDPointFieldIndex, currentNode.uid);
                        }
                        if (osmVisiblePointFieldIndex != -1)
                        {
                            newPointFeature.set_Value(osmVisiblePointFieldIndex, currentNode.visible);
                        }
                        if (osmVersionPointFieldIndex != -1)
                        {
                            newPointFeature.set_Value(osmVersionPointFieldIndex, Convert.ToInt32(currentNode.version));
                        }
                        if (osmChangesetPointFieldIndex != -1)
                        {
                            newPointFeature.set_Value(osmChangesetPointFieldIndex, Convert.ToInt32(currentNode.changeset));
                        }
                        if (osmTimeStampPointFieldIndex != -1)
                        {
                            newPointFeature.set_Value(osmTimeStampPointFieldIndex, Convert.ToDateTime(currentNode.timestamp));
                        }
                        if (osmIDPointFieldIndex != -1)
                        {
                            newPointFeature.set_Value(osmIDPointFieldIndex, Convert.ToInt32(currentNode.id));
                        }

                        _osmUtility.insertOSMTags(tagCollectionPointFieldIndex, newPointFeature, currentNode.tag);

                        newPointFeature.Store();
                 //   }
                }
            }
        }
        protected override void OnClick()
        {
            // Create two points.
            IPoint fromPoint = new Point();

            fromPoint.PutCoords(1300757, 554219);
            IPoint toPoint = new Point();

            toPoint.PutCoords(1300759, 554217);
            // Note: Spatial Reference = NAD_1983_StatePlane_Washington_North_FIPS_4601_Feet

            // ****** No Need to go through IPointCollection  ****

            //// Add the points to a point collection
            //object missing = Type.Missing;
            //IPointCollection pointCollection = new Multipoint();
            //pointCollection.AddPoint(fromPoint, ref missing, ref missing);
            //pointCollection.AddPoint(toPoint, ref missing, ref missing);

            // ****** No Need to go through IPointCollection  ****


            // Get a reference to a feature class from ArcMap
            IMap          map          = ArcMap.Document.ActiveView as IMap;
            ILayer        layer        = map.get_Layer(0);
            IFeatureLayer featureLayer = layer as FeatureLayer;
            IFeatureClass featureClass = featureLayer.FeatureClass;
            IFeature      feature      = featureClass.CreateFeature();

            IPolyline polyline = new PolylineClass();

            polyline.FromPoint = fromPoint;
            polyline.ToPoint   = toPoint;

            //IPolyline polyline = pointCollection as IPolyline; // This leads to a null polyline
            feature.Shape = polyline as IGeometry;
            feature.Store();

            // ---- Symbolize the polyline with the ArrorMarker at both ends of the line -----------
            // See: http://resources.arcgis.com/en/help/arcobjects-net/conceptualhelp/index.html#//0001000008w8000000

            ICartographicLineSymbol ipArrowLineSymbol = new CartographicLineSymbol();

            // the line color will be red
            IRgbColor ipRgbRedColor = new RgbColorClass();

            ipRgbRedColor.Red = 192;

            // the arrow will be black
            IRgbColor ipRgbBlackColor = new RgbColorClass();

            ipRgbBlackColor.RGB = 0;

            // set up the arrow that will be displayed along the line
            IArrowMarkerSymbol ipArrowMarker = new ArrowMarkerSymbolClass();

            ipArrowMarker.Style  = esriArrowMarkerStyle.esriAMSPlain;
            ipArrowMarker.Length = 18;
            ipArrowMarker.Width  = 12;
            ipArrowMarker.Color  = ipRgbBlackColor;

            // set up the line itself
            ipArrowLineSymbol.Width = 4;
            ipArrowLineSymbol.Color = ipRgbRedColor;

            // decorate the line with the arrow symbol
            ISimpleLineDecorationElement ipSimpleLineDecorationElement = new SimpleLineDecorationElementClass();

            ipSimpleLineDecorationElement.Rotate          = true;
            ipSimpleLineDecorationElement.PositionAsRatio = true;
            ipSimpleLineDecorationElement.MarkerSymbol    = ipArrowMarker;
            ipSimpleLineDecorationElement.AddPosition(0.0);
            ipSimpleLineDecorationElement.AddPosition(1.0);
            ipSimpleLineDecorationElement.FlipFirst = true;
            ILineDecoration ipLineDecoration = new LineDecorationClass();

            ipLineDecoration.AddElement(ipSimpleLineDecorationElement);
            ((ILineProperties)ipArrowLineSymbol).LineDecoration = ipLineDecoration;

            // Create renderer and apply it to the layer
            ISimpleRenderer simpleRenderer = new SimpleRendererClass();

            simpleRenderer.Symbol = ipArrowLineSymbol as ISymbol;
            IGeoFeatureLayer geoFeatureLayer = featureLayer as IGeoFeatureLayer;

            geoFeatureLayer.Renderer = simpleRenderer as IFeatureRenderer;

            IMxDocument mxDocument = ArcMap.Application.Document as IMxDocument;

            mxDocument.ActiveView.Refresh();
            mxDocument.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, geoFeatureLayer, mxDocument.ActiveView.Extent);
            mxDocument.UpdateContents();

            // ---- Symbolize the polyline with the ArrorMarker at both ends of the line -----------



            ArcMap.Application.CurrentTool = null;
        }
Esempio n. 18
0
        public static bool Append3DFile(string str3DFile, IFeatureClass fClassTarget , string strSpatialRef, ref IFeature feature3D)
        {
            try
            {

                string strTempPath=System.IO.Path.GetPathRoot(System.Environment.SystemDirectory);
                string strOutputTemp = System.IO.Path.Combine(strTempPath, "temp.shp");

                if (System.IO.File.Exists(strOutputTemp) && !DeleteDataset(strOutputTemp))
                {
                    ErrorMessage = "无法使用临时文件";
                    return false;
                }

                if (!Import3DFile(str3DFile, strOutputTemp, strSpatialRef))
                {
                    return false;
                }

                IWorkspace wsTemp =Hy.Esri.Utility.WorkspaceHelper.OpenWorkspace(Hy.Esri.Utility.enumWorkspaceType.File, strTempPath);
                IFeatureClass fClassTemp = (wsTemp as IFeatureWorkspace).OpenFeatureClass("temp");
                IFeatureCursor fCursorTemp = fClassTemp.Search(null, false);
                IFeature fTemp = fCursorTemp.NextFeature();
                if (fTemp == null)
                {
                    ErrorMessage = "追加的中转过程出错!";
                    return false;
                }
                IGeometry geo3D = (fTemp.Shape as IClone).Clone() as IGeometry;

                //IFeatureClass fClass = (wsTarget as IFeatureWorkspace).OpenFeatureClass(featureClassName);
                //feature3D = fClass.CreateFeature();
                feature3D = fClassTarget.CreateFeature();
                feature3D.Shape = geo3D;
                feature3D.Store();

                System.Runtime.InteropServices.Marshal.ReleaseComObject(fTemp);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(fCursorTemp);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(fClassTemp);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wsTemp);

                return true;

                //string outPut = WorkspaceHelper.GetGpString(wsTarget, featrueDatasetName, featureClassName);
                //IFeature newFeature = null;
                //Append gpAppend = new Append();
                //gpAppend.inputs = strOutputTemp;
                //gpAppend.output = newFeature;
                //gpAppend.target = outPut;

                //Geoprocessor geoProcessor = new Geoprocessor();
                //geoProcessor.OverwriteOutput = true;
                //IGeoProcessorResult gpResult = geoProcessor.Execute(gpAppend, null) as IGeoProcessorResult;

                //return gpResult.Status == esriJobStatus.esriJobSucceeded;
            }
            catch(Exception exp)
            {
                ErrorMessage = exp.Message;
                return false;
            }
        }
        /*
         * A function to populate a referenced FeatureClass (fc) with the contents of a Google Maps Engine map
         */
        public void populateFCWithGoogleMapsEngineMap(ref IFeatureClass fc, ref MapsEngine.DataModel.gme.Map map)
        {
            // create a feature object
            log.Debug("Creating a new Feature object to be used later in populating the FC.");
            IFeature feature = fc.CreateFeature();

            log.Debug("Creating feature for map " + map.id);

            // create a projectId value from the MapId
            String projectId = map.id.Split("-".ToCharArray())[0];

            // Update the values for this feature
            feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_CustomerId_Name), projectId);
            log.Debug(Properties.Resources.GeodatabaseUtilities_schema_CustomerId_Name + ": " + projectId);
            feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_AssetId_Name), map.id);
            log.Debug(Properties.Resources.GeodatabaseUtilities_schema_AssetId_Name + ": " + map.id);
            feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_MapAssetId_Name), map.id);
            log.Debug(Properties.Resources.GeodatabaseUtilities_schema_MapAssetId_Name + ": " + map.id);
            feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_AssetType_Name), "map");
            log.Debug(Properties.Resources.GeodatabaseUtilities_schema_AssetType_Name + ": " + "map");
            feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_AssetName_Name), map.name);
            log.Debug(Properties.Resources.GeodatabaseUtilities_schema_AssetName_Name + ": " + map.name);
            feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_ParentAssetId_Name), projectId);
            log.Debug(Properties.Resources.GeodatabaseUtilities_schema_ParentAssetId_Name + ": " + projectId);

            // attempt to set the description
            try
            {
                // attempt to set the feature description (truncating if necessary)
                feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_AssetDescription_Name)
                                  , map.description.Length > 256
                    ? map.description.Substring(0, 252) + "..."
                    : map.description);
                log.Debug(Properties.Resources.GeodatabaseUtilities_schema_AssetDescription_Name + ": " + map.description);
            }
            catch (System.Exception ex)
            {
                // warn
                log.Warn(ex);
            }

            // check to see if the bbox object is not null
            log.Debug("Adding spatial representation if available.");
            if (map.bbox != null && map.bbox.Count() == 4)
            {
                // deterine the maximum and minimum bounds of all layers within this map
                // 0=West, 1=South, 2=East, 3=North
                double XMAX = map.bbox[2];
                log.Debug("XMAX: " + XMAX);
                double YMAX = map.bbox[3];
                log.Debug("YMAX: " + YMAX);
                double XMIN = map.bbox[0];
                log.Debug("XMIN: " + XMIN);
                double YMIN = map.bbox[1];
                log.Debug("YMIN: " + YMIN);


                // determine the map extent based on the layers maximum extent
                IPoint pExtentNE = new Point();
                pExtentNE.X = XMAX;
                pExtentNE.Y = YMAX;
                IPoint pExtentSW = new Point();
                pExtentSW.X = XMIN;
                pExtentSW.Y = YMIN;
                IPoint pExtentNW = new Point();
                pExtentNW.X = XMIN;
                pExtentNW.Y = YMAX;
                IPoint pExtentSE = new Point();
                pExtentSE.X = XMAX;
                pExtentSE.Y = YMIN;

                // define the polygon bounding box (NE/SW) as a point collection
                log.Debug("Building polygon object.");
                IPointCollection pExtentPointCol = new Polygon();
                pExtentPointCol.AddPoint(pExtentNE, Type.Missing, Type.Missing);
                pExtentPointCol.AddPoint(pExtentSE, Type.Missing, Type.Missing);
                pExtentPointCol.AddPoint(pExtentSW, Type.Missing, Type.Missing);
                pExtentPointCol.AddPoint(pExtentNW, Type.Missing, Type.Missing);

                // create a polygon, p, from the point collection, then close the polygon
                IPolygon pExtent = (IPolygon)pExtentPointCol;
                pExtent.Close();

                // add the polygon, p, as the new feature's geometry
                if (pExtent != null)
                {
                    log.Debug("Setting feature's geometry.");
                    feature.Shape = pExtent;
                }
                else
                {
                    log.Warn("Polygon is not valid, setting feature geometry to default worldwide.");
                    feature.Shape = worldPolygon;
                }
            }
            else
            {
                // no spatial information contained, use world
                log.Warn("No spatial representation, setting feature geometry to default worldwide.");
                //feature.Shape = worldPolygon;
            }

            // Commit the new feature to fc
            log.Debug("Storing feature.");
            feature.Store();

            // add all child layers within this map
            log.Debug("Verifying the map has layers.");
            if (map.layers != null)
            {
                // go through each layer in the map
                log.Debug("Going through each layer in the map.");
                foreach (MapsEngine.DataModel.gme.MapLayer layer in map.layers)
                {
                    // populate the features in the layer
                    log.Debug("Processing layer " + layer.id);
                    populateFCWithGoogleMapsEngineLayer(ref fc, map.id, map.id, layer);
                }
            }

            // Verifying the map has a folders object
            log.Debug("Verifying the map has a folders object.");
            if (map.folders != null && map.folders.Count() > 0)
            {
                // populate the features in the folder
                log.Debug("Processing folders");
                populateFCWithGoogleMapsEngineFolders(ref fc, map.id, map.id, map.folders);
            }
        }
Esempio n. 20
0
        private static void VerifyPolyErrorHasZ(IFeatureWorkspace ws)
        {
            IFieldsEdit fields = new FieldsClass();

            fields.AddField(FieldUtils.CreateOIDField());
            fields.AddField(FieldUtils.CreateShapeField(
                                "Shape", esriGeometryType.esriGeometryPolygon,
                                SpatialReferenceUtils.CreateSpatialReference
                                    ((int)esriSRProjCS2Type.esriSRProjCS_CH1903Plus_LV95,
                                    true), 1000, true, false));

            IFeatureClass featureClass =
                DatasetUtils.CreateSimpleFeatureClass(ws, "VerifyPolyErrorHasZ", fields,
                                                      null);

            // make sure the table is known by the workspace
            ((IWorkspaceEdit)ws).StartEditing(false);
            ((IWorkspaceEdit)ws).StopEditing(true);

            IPolycurve poly1 = CurveConstruction.StartPoly(0, 0, 5.03)
                               .LineTo(-10, -1, 4.99)
                               .LineTo(-10, 1, 5.02)
                               .ClosePolygon();
            IFeature row1 = featureClass.CreateFeature();

            row1.Shape = poly1;
            row1.Store();

            IPolycurve poly2 = CurveConstruction.StartPoly(10, -1, 4.94)
                               .LineTo(0, 0, 5.01)
                               .LineTo(10, 1, 4.97)
                               .ClosePolygon();
            IFeature row2 = featureClass.CreateFeature();

            row2.Shape = poly2;
            row2.Store();

            var test = new QaNotNear(featureClass, featureClass, 0.1, 0.1, is3D: true);

            test.IgnoreNeighborCondition = "G1.ObjectId = G2.ObjectId";

            var runners =
                new List <QaTestRunnerBase>
            {
                new QaTestRunner(test)
                {
                    KeepGeometry = true
                },
                new QaContainerTestRunner(1000, test)
                {
                    KeepGeometry = true
                }
            };

            foreach (QaTestRunnerBase runner in runners)
            {
                runner.Execute();
                Assert.True(runner.ErrorGeometries.Count > 0);
                foreach (IGeometry errorGeometry in runner.ErrorGeometries)
                {
                    Assert.True(errorGeometry.Envelope.ZMin > 4);
                }
            }
        }
        /*
         * A function to populate a referenced Feature Class (fc) with the contents of a Google Maps Engine map layer
         */
        protected void populateFCWithGoogleMapsEngineLayer(ref IFeatureClass fc, string mapId, string parentId, MapsEngine.DataModel.gme.MapLayer layer)
        {
            // create a new feature
            IFeature feature;

            log.Debug("Creating a feature for layer " + layer.id);

            // attempt to process the assets within a the layer
            try
            {
                // fetch the layer asset object from the API
                log.Debug("Fetching an asset object for the layer.");
                MapsEngine.DataModel.gme.Asset layerAsset = api.getAssetById(ext.getToken(), layer.id);

                // create a new feature
                log.Debug("Creating a new feature.");
                feature = fc.CreateFeature();

                // Update the values for this feature
                feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_CustomerId_Name), mapId.Split("-".ToCharArray())[0]);
                log.Debug(Properties.Resources.GeodatabaseUtilities_schema_CustomerId_Name + ": " + mapId.Split("-".ToCharArray())[0]);
                feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_AssetId_Name), layer.id);
                log.Debug(Properties.Resources.GeodatabaseUtilities_schema_AssetId_Name + ": " + layer.id);
                feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_MapAssetId_Name), mapId);
                log.Debug(Properties.Resources.GeodatabaseUtilities_schema_MapAssetId_Name + ": " + mapId);
                feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_AssetType_Name), layerAsset.type);
                log.Debug(Properties.Resources.GeodatabaseUtilities_schema_AssetType_Name + ": " + layerAsset.type);
                feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_AssetName_Name), layerAsset.name);
                log.Debug(Properties.Resources.GeodatabaseUtilities_schema_AssetName_Name + ": " + layerAsset.name);
                feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_ParentAssetId_Name), parentId);
                log.Debug(Properties.Resources.GeodatabaseUtilities_schema_ParentAssetId_Name + ": " + parentId);

                // attempt to set the description object
                try
                {
                    // set the layer description value (truncate if necessary)
                    feature.set_Value(fc.FindField(Properties.Resources.GeodatabaseUtilities_schema_AssetDescription_Name)
                                      , layerAsset.description.Length > 256
                        ? layerAsset.description.Substring(0, 252) + "..."
                        : layerAsset.description);
                    log.Debug(Properties.Resources.GeodatabaseUtilities_schema_AssetDescription_Name + ": " + layerAsset.description);
                }
                catch (System.Exception ex)
                {
                    // log warning
                    log.Warn(ex);
                }

                // verify the layer has a bbox and has two valid points
                if (layerAsset.bbox != null && layerAsset.bbox.Count() == 4)
                {
                    // deterine the maximum and minimum bounds of all layers within this map
                    // 0=West, 1=South, 2=East, 3=North
                    double XMAX = layerAsset.bbox[2];
                    log.Debug("XMAX: " + XMAX);
                    double YMAX = layerAsset.bbox[3];
                    log.Debug("YMAX: " + YMAX);
                    double XMIN = layerAsset.bbox[0];
                    log.Debug("XMIN: " + XMIN);
                    double YMIN = layerAsset.bbox[1];
                    log.Debug("YMIN: " + YMIN);

                    // determine the map extent based on the layers maximum extent
                    IPoint pExtentNE = new Point();
                    pExtentNE.X = XMAX;
                    pExtentNE.Y = YMAX;
                    IPoint pExtentSW = new Point();
                    pExtentSW.X = XMIN;
                    pExtentSW.Y = YMIN;
                    IPoint pExtentNW = new Point();
                    pExtentNW.X = XMIN;
                    pExtentNW.Y = YMAX;
                    IPoint pExtentSE = new Point();
                    pExtentSE.X = XMAX;
                    pExtentSE.Y = YMIN;

                    // define the polygon bounding box (NE/SW) as a point collection
                    IPointCollection pExtentPointCol = new Polygon();
                    pExtentPointCol.AddPoint(pExtentNE, Type.Missing, Type.Missing);
                    pExtentPointCol.AddPoint(pExtentSE, Type.Missing, Type.Missing);
                    pExtentPointCol.AddPoint(pExtentSW, Type.Missing, Type.Missing);
                    pExtentPointCol.AddPoint(pExtentNW, Type.Missing, Type.Missing);

                    // create a polygon, p, from the point collection, then close the polygon
                    IPolygon pExtent = (IPolygon)pExtentPointCol;
                    pExtent.Close();

                    // add the polygon, p, as the new feature's geometry
                    if (pExtent != null)
                    {
                        // set the shape geometry
                        log.Debug("Setting the feature's geometry as the polygon.");
                        feature.Shape = pExtent;
                    }
                    else
                    {
                        // set the feature's goemetry as the default world
                        log.Debug("Invalid spatial representation, setting feature goemtry as the world.");
                        feature.Shape = worldPolygon;
                    }
                }
                else
                {
                    // the layer does not have spatial information
                    log.Warn("Layer has no bbox information");
                    //feature.Shape = worldPolygon;
                }

                // Commit the new feature to fc
                log.Debug("Storing feature.");
                feature.Store();
            }
            catch (Exception ex)
            {
                // log the warning
                log.Warn(ex);
            }
        }
Esempio n. 22
0
        /// <summary>
        /// 创建回采进尺线(根据参考线创建平行线)
        /// </summary>
        /// <param name="featureLayer">回采进尺图层</param>
        /// <param name="pRefPolyline">参考开切眼巷道</param>
        /// <param name="dDistance">回采距离</param>
        /// <returns>成功创建返回True</returns>
        public static bool CreateParaLineFeature(IFeatureLayer featureLayer, IPolyline pRefPolyline, string bindID, double dDistance)
        {
            if (pRefPolyline == null || pRefPolyline.IsEmpty)
            {
                return(false);
            }

            try
            {
                IFeatureClass featureClass = featureLayer.FeatureClass;
                IGeometry     geometry     = pRefPolyline;

                object          Missing        = Type.Missing;
                IConstructCurve constructCurve = new PolylineClass();
                constructCurve.ConstructOffset(pRefPolyline, dDistance, ref Missing, ref Missing);

                IPolyline hcLine = constructCurve as IPolyline;
                if (featureClass.ShapeType == esriGeometryType.esriGeometryPolyline)
                {
                    IDataset       dataset       = (IDataset)featureClass;
                    IWorkspace     workspace     = dataset.Workspace;
                    IWorkspaceEdit workspaceEdit = workspace as IWorkspaceEdit;
                    workspaceEdit.StartEditOperation();
                    IFeature feature = featureClass.CreateFeature();

                    Common.DataEditCommon.ZMValue(feature, hcLine);  //几何图形Z值处理

                    feature.Shape = hcLine;

                    //绑定唯一编号
                    int iFieldID = feature.Fields.FindField("ID");
                    if (iFieldID > -1)
                    {
                        feature.Value[iFieldID] = bindID;
                    }

                    //回采距离
                    iFieldID = feature.Fields.FindField("Distance");
                    if (iFieldID > -1)
                    {
                        feature.Value[iFieldID] = dDistance;
                    }

                    feature.Store();
                    workspaceEdit.StopEditOperation();

                    //缩放到新增的线要素,并高亮该要素
                    GIS.Common.DataEditCommon.g_pMyMapCtrl.ActiveView.Extent = hcLine.Envelope;
                    GIS.Common.DataEditCommon.g_pMyMapCtrl.ActiveView.Extent.Expand(1.5, 1.5, true);
                    GIS.Common.DataEditCommon.g_pMyMapCtrl.Map.SelectFeature(featureLayer, feature);
                    GIS.Common.DataEditCommon.g_pMyMapCtrl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewAll, null, null);
                    //GIS.Common.DataEditCommon.g_pMyMapCtrl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewBackground, null, null);
                    return(true);
                }
                else
                {
                    //System.Windows.Forms.MessageBox.Show("请选择点图层。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return(false);
                }
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 23
0
        private bool CreateShpFile(List <ROIGeometry> geometryList, out string sShpFilePath)
        {
            bool   result  = false;
            string shpName = DateTime.Now.ToString("yyyyMMddhhmmss");

            sShpFilePath = System.IO.Path.Combine(ConstDef.PATH_TEMP, shpName + ".shp");
            try
            {
                if (!Directory.Exists(ConstDef.PATH_TEMP))
                {
                    Directory.CreateDirectory(ConstDef.PATH_TEMP);
                }
                IWorkspace workspace = EngineAPI.OpenWorkspace(ConstDef.PATH_TEMP, DataType.shp);
                if (workspace == null)
                {
                    result = false;
                }
                else
                {
                    IFields fields = this.CreateFields();
                    if (fields == null)
                    {
                        result = false;
                    }
                    IFeatureClass featureClass = this.CreateFeatureClass(workspace, shpName, fields, spatialReference);
                    if (featureClass == null)
                    {
                        result = false;
                    }
                    try
                    {
                        int rowIndex = 0;
                        foreach (ROIGeometry roi in geometryList)
                        {
                            IFeature pFeature = featureClass.CreateFeature();
                            pFeature.Shape = roi.geometry;
                            pFeature.Store();

                            ITable pTable = pFeature.Table;
                            if (pTable.RowCount(null) > 0)
                            {
                                IRow pRow = pTable.GetRow(rowIndex);
                                pRow.set_Value(2, roi.name);
                                pRow.set_Value(3, roi.id);
                                pRow.set_Value(4, roi.color);
                                pRow.Store();
                            }
                            rowIndex++;
                            //IFieldEdit field = feature as IField;
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLog(typeof(NeuralNet), ex);
                        result = false;
                    }
                    finally
                    {
                        if (featureClass != null)
                        {
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(featureClass);
                        }
                    }
                }
                result = true;
            }
            catch (Exception ex)
            {
                Log.WriteLog(typeof(NeuralNet), ex);
                result = false;
            }

            return(result);
        }
Esempio n. 24
0
        private void buttonX_ok_Click(object sender, EventArgs e)
        {
            //add all point
            List <IPoint> pointList = new List <IPoint>();
            //add point type
            List <string> typeList = new List <string>();
            //read excel file to creat Field
            string          strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + this.textBoxX1.Text + ";Extended Properties=Excel 8.0";
            OleDbConnection conn   = new OleDbConnection(strCon);
            string          sql1   = "select * from [Sheet1$]";

            conn.Open();
            OleDbDataAdapter myCommand = new OleDbDataAdapter(sql1, strCon);
            DataSet          ds        = new DataSet();

            myCommand.Fill(ds);
            conn.Close();

            ISpatialReference pSpaReference = new UnknownCoordinateSystemClass();

            pSpaReference.SetDomain(-8000000, 8000000, -800000, 8000000);
            IFeatureClass pFt = CreateShapeFile(ds, this.textBoxX2.Text, pSpaReference);

            int xindex = 18;
            int yindex = 19;
            int zindex = 20;

            if (ds.Tables[0].Columns[19].ColumnName.ToString().Contains("东坐标"))
            {
                xindex++;
                yindex++;
                zindex++;
            }

            if (pFt == null)
            {
                return;
            }
            else
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    //get type
                    string typeTemp = ds.Tables[0].Rows[i][3].ToString();
                    typeTemp = typeTemp.Split(new char[1] {
                        ' '
                    })[0];
                    //根据XY坐标添加点,edit attribute
                    IsNumberic isNum  = new IsNumberic();
                    IPoint     pPoint = new PointClass();
                    if (isNum.IsNumber(ds.Tables[0].Rows[i][xindex].ToString()) && isNum.IsNumber(ds.Tables[0].Rows[i][yindex].ToString()))
                    {
                        pPoint.X = System.Convert.ToDouble(ds.Tables[0].Rows[i][xindex].ToString());
                        pPoint.Y = System.Convert.ToDouble(ds.Tables[0].Rows[i][yindex].ToString());
                        pPoint.Z = System.Convert.ToDouble(ds.Tables[0].Rows[i][zindex].ToString());
                        IFeature pFeature = pFt.CreateFeature();
                        pFeature.Shape = pPoint;

                        pFeature.Store();
                        for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                        {
                            //pFeature.set_Value(pFeature.Fields.FindField(ds.Tables[0].Columns[j].ColumnName), ds.Tables[0].Rows[i][j]);
                            pFeature.set_Value(j + 2, ds.Tables[0].Rows[i][j].ToString());
                        }
                        pFeature.set_Value(pFeature.Fields.FindField("Type"), typeTemp);
                        pFeature.Store();

                        pointList.Add(pPoint);
                    }
                    else
                    {
                        MessageBox.Show("the" + i + "rows x and y value is unvalid!");
                    }
                }
            }

            ClsGDBDataCommon processDataCommon = new ClsGDBDataCommon();
            string           strInputPath      = System.IO.Path.GetDirectoryName(textBoxX2.Text);
            string           strInputName      = System.IO.Path.GetFileName(textBoxX2.Text);

            IFeatureLayer pFeatureLayer = new FeatureLayerClass();

            pFeatureLayer.FeatureClass = pFt;
            pFeatureLayer.Name         = System.IO.Path.GetFileNameWithoutExtension(System.IO.Path.GetFileNameWithoutExtension(strInputName)) + "_point";

            //create line shape file
            IPointCollection PointCollection = ReadPoint(pFeatureLayer);
            string           lineName        = strInputPath + "\\" + System.IO.Path.GetFileNameWithoutExtension(strInputName) + "_line.shp";

            CreateLineShpFile(lineName, pSpaReference);
            //将所有的点连接成线
            List <IPolyline> Polyline       = CreatePolyline(PointCollection);
            List <double>    lineLengthList = new List <double>();
            //将连接成的线添加到线图层中
            string pLineFile = lineName;
            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 plineLayer = new FeatureLayerClass();

            plineLayer.FeatureClass = pWS.OpenFeatureClass(pFileName);
            AddFeature(plineLayer, Polyline, pointList, lineLengthList);
            plineLayer.Name = pFeatureLayer.Name + "_line";

            m_pMapCtl.AddLayer(plineLayer as ILayer, 0);
            m_pMapCtl.AddLayer(pFeatureLayer as ILayer, 0);
            m_pMapCtl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);

            ImpSymbolFromFile(textBoxX3.Text, pFeatureLayer, plineLayer);

            //export doc file
            string TemplateFileName = ClsGDBDataCommon.GetParentPathofExe() + @"Resource\WordTemplate\内检测报告.doc";

            exportDocFile(TemplateFileName, textBoxX4.Text, lineLengthList);

            //#region 读取SHP文件
            //IWorkspace pWorkspace = processDataCommon.OpenFromShapefile(strInputPath);
            //IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace;
            //IFeatureClass pInputFC = pFeatureWorkspace.OpenFeatureClass(strInputName);
            //#endregion

            //IFeatureLayer pFeatureLayer = new FeatureLayerClass();
            //pFeatureLayer.FeatureClass = pInputFC;
            //pFeatureLayer.Name = strInputName;
            //m_pMapCtl.AddLayer(pFeatureLayer as ILayer, 0);
            //m_pMapCtl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);

            this.Close();
        }
Esempio n. 25
0
        private void btnCreate_Click(object sender, EventArgs e)
        {
            try
            {
                frmProgress pfrmProgress = new frmProgress();
                pfrmProgress.bgWorker.ReportProgress(0);
                pfrmProgress.lblStatus.Text = "Create Flow Lines";
                pfrmProgress.Show();

                string            strOutput     = txtOutput.Text;
                string            strOutputPath = System.IO.Path.GetDirectoryName(strOutput);
                string            strOutputName = System.IO.Path.GetFileName(strOutput);
                ISpatialReference pSpatialRef   = null;
                if (cboSpatialInfo.Text == "From ShapeFile")
                {
                    IGeoDataset geoDataset = m_pFClass as IGeoDataset;
                    pSpatialRef = geoDataset.SpatialReference;
                }

                //Create New FeatureClass
                IFeatureClass pFCOutput = CreateShapeFile(strOutputPath, strOutputName, pSpatialRef, esriGeometryType.esriGeometryPolyline);

                //Add Fld Ids to added in new FC
                int[] intAddFldIdsInTable = null;
                int   intCheckedFldCnt    = clistFields.CheckedItems.Count;
                if (intCheckedFldCnt > 0)
                {
                    intAddFldIdsInTable = new int[intCheckedFldCnt];
                    for (int i = 0; i < intCheckedFldCnt; i++)
                    {
                        intAddFldIdsInTable[i] = m_tblFlow.FindField((string)clistFields.CheckedItems[i]);
                    }
                }
                AddFldsFromTable(pFCOutput, m_tblFlow, intAddFldIdsInTable);
                //Get Ids from FeatureClass
                int[] intAddFldIdsInFC = null;

                if (intCheckedFldCnt > 0)
                {
                    intAddFldIdsInFC = new int[intCheckedFldCnt];
                    for (int i = 0; i < intCheckedFldCnt; i++)
                    {
                        intAddFldIdsInFC[i] = pFCOutput.FindField((string)clistFields.CheckedItems[i]);
                    }
                }
                var watch = Stopwatch.StartNew();


                if (cboSpatialInfo.Text == "From Table")
                {
                    //First Method, it takes some times, require better algorithm. 0714 HK
                    string strFromXFld = cbo1.Text;
                    string strFromYFld = cbo2.Text;
                    string strToXFld   = cbo3.Text;
                    string strToYFld   = cbo4.Text;

                    int intFromXIdx = m_tblFlow.FindField(strFromXFld);
                    int intFromYIdx = m_tblFlow.FindField(strFromYFld);
                    int intToXIdx   = m_tblFlow.FindField(strToXFld);
                    int intToYIdx   = m_tblFlow.FindField(strToYFld);

                    int     intTotalFlowCnt = m_tblFlow.RowCount(null);
                    ICursor pCursor         = m_tblFlow.Search(null, false);
                    IRow    pRow            = pCursor.NextRow();
                    //IPoint pFromPt = new ESRI.ArcGIS.Geometry.Point();
                    //IPoint pToPts = new ESRI.ArcGIS.Geometry.Point();
                    IPoint pFromPt = null;
                    IPoint pToPt = null;
                    double dblFromX = 0, dblFromY = 0, dblToX = 0, dblToY = 0;

                    IPolyline pPolyline = new PolylineClass();

                    int cnt = 0;
                    if (intCheckedFldCnt > 0)
                    {
                        while (pRow != null)
                        {
                            int intProgress = cnt * 100 / intTotalFlowCnt;
                            pfrmProgress.bgWorker.ReportProgress(intProgress);

                            dblFromX = Convert.ToDouble(pRow.get_Value(intFromXIdx));
                            dblFromY = Convert.ToDouble(pRow.get_Value(intFromYIdx));
                            dblToX   = Convert.ToDouble(pRow.get_Value(intToXIdx));
                            dblToY   = Convert.ToDouble(pRow.get_Value(intToYIdx));

                            pFromPt = new PointClass();
                            pToPt   = new PointClass();
                            pFromPt.PutCoords(dblFromX, dblFromY);
                            pToPt.PutCoords(dblToX, dblToY);

                            pPolyline           = new PolylineClass();
                            pPolyline.FromPoint = pFromPt;
                            pPolyline.ToPoint   = pToPt;
                            IFeature pFeature = pFCOutput.CreateFeature();
                            pFeature.Shape = pPolyline;

                            for (int i = 0; i < intCheckedFldCnt; i++)
                            {
                                pFeature.set_Value(intAddFldIdsInFC[i], pRow.get_Value(intAddFldIdsInTable[i]));
                            }

                            pFeature.Store();
                            pRow = pCursor.NextRow();
                            cnt++;
                        }
                    }
                    else
                    {
                        int intProgress = cnt * 100 / intTotalFlowCnt;
                        pfrmProgress.bgWorker.ReportProgress(intProgress);

                        dblFromX = Convert.ToDouble(pRow.get_Value(intFromXIdx));
                        dblFromY = Convert.ToDouble(pRow.get_Value(intFromYIdx));
                        dblToX   = Convert.ToDouble(pRow.get_Value(intToXIdx));
                        dblToY   = Convert.ToDouble(pRow.get_Value(intToYIdx));

                        pFromPt = new PointClass();
                        pToPt   = new PointClass();
                        pFromPt.PutCoords(dblFromX, dblFromY);
                        pToPt.PutCoords(dblToX, dblToY);

                        pPolyline           = new PolylineClass();
                        pPolyline.FromPoint = pFromPt;
                        pPolyline.ToPoint   = pToPt;
                        IFeature pFeature = pFCOutput.CreateFeature();
                        pFeature.Shape = pPolyline;

                        pFeature.Store();
                        pRow = pCursor.NextRow();
                        cnt++;
                    }
                    #region deprecated 101917 HK
                    //    //Second Method, it takes similar calculation time. 0714 HK
                    //    string strFromXFld = cbo1.Text;
                    //    string strFromYFld = cbo2.Text;
                    //    string strToXFld = cbo3.Text;
                    //    string strToYFld = cbo4.Text;

                    //    int intFromXIdx = m_tblFlow.FindField(strFromXFld);
                    //    int intFromYIdx = m_tblFlow.FindField(strFromYFld);
                    //    int intToXIdx = m_tblFlow.FindField(strToXFld);
                    //    int intToYIdx = m_tblFlow.FindField(strToYFld);

                    //    int intTotalFlowCnt = m_tblFlow.RowCount(null);
                    //    ICursor pCursor = m_tblFlow.Search(null, false);
                    //    IRow pRow = pCursor.NextRow();
                    //    //IPoint pFromPt = new ESRI.ArcGIS.Geometry.Point();
                    //    //IPoint pToPts = new ESRI.ArcGIS.Geometry.Point();
                    //    IPoint pFromPt = null;
                    //    IPoint pToPt = null;

                    //    IPolyline pPolyline = new PolylineClass();

                    //    double[][] dblValues = new double[intTotalFlowCnt][];
                    //    int cnt = 0;
                    //    while (pRow != null)
                    //    {
                    //        pfrmProgress.lblStatus.Text = "Collect data";
                    //        int intProgress = cnt * 100 / intTotalFlowCnt;
                    //        pfrmProgress.bgWorker.ReportProgress(intProgress);


                    //        dblValues[cnt] = new double[4 + intCheckedFldCnt];

                    //        dblValues[cnt][0] = Convert.ToDouble(pRow.get_Value(intFromXIdx));
                    //        dblValues[cnt][1] = Convert.ToDouble(pRow.get_Value(intFromYIdx));
                    //        dblValues[cnt][2] = Convert.ToDouble(pRow.get_Value(intToXIdx));
                    //        dblValues[cnt][3] = Convert.ToDouble(pRow.get_Value(intToYIdx));

                    //        if (intCheckedFldCnt > 0)
                    //            for (int i = 0; i < intCheckedFldCnt; i++)
                    //                dblValues[cnt][3+i] = Convert.ToDouble(pRow.get_Value(intAddFldIdsInTable[i]));

                    //        pRow = pCursor.NextRow();
                    //        cnt++;
                    //    }
                    //    for(int j = 0; j<intTotalFlowCnt; j++)
                    //    {
                    //        pfrmProgress.lblStatus.Text = "Create Line";
                    //        int intProgress = j * 100 / intTotalFlowCnt;
                    //        pfrmProgress.bgWorker.ReportProgress(intProgress);

                    //        pFromPt = new PointClass();
                    //        pToPt = new PointClass();
                    //        pFromPt.PutCoords(dblValues[j][0], dblValues[j][1]);
                    //        pToPt.PutCoords(dblValues[j][2], dblValues[j][3]);

                    //        pPolyline = new PolylineClass();
                    //        pPolyline.FromPoint = pFromPt;
                    //        pPolyline.ToPoint = pToPt;
                    //        IFeature pFeature = pFCOutput.CreateFeature();
                    //        pFeature.Shape = pPolyline;
                    //        if (intCheckedFldCnt > 0)
                    //            for (int i = 0; i < intCheckedFldCnt; i++)
                    //                pFeature.set_Value(intAddFldIdsInFC[i], dblValues[j][3+i]);

                    //        pFeature.Store();
                    //    }
                    #endregion
                }
                else if (cboSpatialInfo.Text == "From ShapeFile")
                {
                    string strRefSHPName  = cbo1.Text;
                    string strJoinFldName = cbo2.Text;
                    string strOIDFldName  = cbo3.Text;
                    string strDIDFldName  = cbo4.Text;

                    int intJoinFldIdx = m_pFClass.FindField(strJoinFldName);
                    int intOIDIdx     = m_tblFlow.FindField(strOIDFldName);
                    int intDIDIdx     = m_tblFlow.FindField(strDIDFldName);

                    int intFeatureCount = m_pFClass.FeatureCount(null);

                    IFeatureCursor pFCursor = m_pFClass.Search(null, true);
                    IFeature       pFeature = pFCursor.NextFeature();

                    List <RefSpatialInfo> lstRefInfo = new List <RefSpatialInfo>();

                    IArea  pArea;
                    IPoint pPoint;

                    int cnt = 0;
                    while (pFeature != null)
                    {
                        pfrmProgress.lblStatus.Text = "Getting Spatial Information from Shape file";
                        int intProgress = cnt * 100 / intFeatureCount;
                        pfrmProgress.bgWorker.ReportProgress(intProgress);

                        RefSpatialInfo RefInfo = new RefSpatialInfo();
                        RefInfo.JoinID = pFeature.get_Value(intJoinFldIdx).ToString();

                        if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                        {
                            pArea         = (IArea)pFeature.Shape;
                            RefInfo.XCoor = pArea.Centroid.X;
                            RefInfo.YCoor = pArea.Centroid.Y;
                        }
                        else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint)
                        {
                            pPoint        = (IPoint)pFeature.Shape;
                            RefInfo.XCoor = pPoint.X;
                            RefInfo.YCoor = pPoint.Y;
                        }

                        lstRefInfo.Add(RefInfo);

                        cnt++;
                        pFeature = pFCursor.NextFeature();
                    }
                    pFCursor.Flush();

                    int     intTotalFlowCnt = m_tblFlow.RowCount(null);
                    ICursor pCursor         = m_tblFlow.Search(null, false);
                    IRow    pRow            = pCursor.NextRow();

                    IPoint pFromPt = null;
                    IPoint pToPt = null;
                    double dblFromX = 0, dblFromY = 0, dblToX = 0, dblToY = 0;

                    IPolyline pPolyline = new PolylineClass();

                    cnt = 0;
                    int intNonMatchedFlow = 0;
                    while (pRow != null)
                    {
                        pfrmProgress.lblStatus.Text = "Create Flow Lines";
                        int intProgress = cnt * 100 / intTotalFlowCnt;
                        pfrmProgress.bgWorker.ReportProgress(intProgress);

                        string strOID = pRow.get_Value(intOIDIdx).ToString();
                        string strDID = pRow.get_Value(intDIDIdx).ToString();

                        RefSpatialInfo RefOInfo = lstRefInfo.Find(x => x.JoinID == strOID);
                        RefSpatialInfo RefDInfo = lstRefInfo.Find(x => x.JoinID == strDID);

                        if (RefOInfo == null || RefDInfo == null)
                        {
                            intNonMatchedFlow++;
                            pRow = pCursor.NextRow();
                            cnt++;
                        }
                        else
                        {
                            dblFromX = RefOInfo.XCoor;
                            dblFromY = RefOInfo.YCoor;
                            dblToX   = RefDInfo.XCoor;
                            dblToY   = RefDInfo.YCoor;

                            pFromPt = new PointClass();
                            pToPt   = new PointClass();
                            pFromPt.PutCoords(dblFromX, dblFromY);
                            pToPt.PutCoords(dblToX, dblToY);

                            pPolyline           = new PolylineClass();
                            pPolyline.FromPoint = pFromPt;
                            pPolyline.ToPoint   = pToPt;
                            IFeature pNewFeature = pFCOutput.CreateFeature();
                            pNewFeature.Shape = pPolyline;

                            if (intCheckedFldCnt > 0)
                            {
                                for (int i = 0; i < intCheckedFldCnt; i++)
                                {
                                    pNewFeature.set_Value(intAddFldIdsInFC[i], pRow.get_Value(intAddFldIdsInTable[i]));
                                }
                            }

                            pNewFeature.Store();
                            pRow = pCursor.NextRow();
                            cnt++;
                        }
                    }
                    //MessageBox.Show(intNonMatchedFlow.ToString()+" flow lines are not matched with the reference file"); //Check the message. 080516 HK
                }
                pfrmProgress.Close();

                watch.Stop();
                double dblTime = watch.ElapsedMilliseconds;
                MessageBox.Show("Run-time: " + dblTime.ToString());

                DialogResult dialogResult = MessageBox.Show("Do you want to add the output data to the map?", "Add Data", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    IFeatureLayer pFeaturelayer = new FeatureLayer();
                    pFeaturelayer.Name         = pFCOutput.AliasName;
                    pFeaturelayer.FeatureClass = pFCOutput;
                    m_pActiveView.FocusMap.AddLayer((ILayer)pFeaturelayer);
                }
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Esempio n. 26
0
        private string Insert(IFeatureClass FC, model Model, IGeometry Geometry)
        {
            try
            {
                IWorkspaceEdit WSE = (FC as IDataset).Workspace as IWorkspaceEdit;
                WSE.StartEditing(false);
                WSE.StartEditOperation();

                IFeature F = FC.CreateFeature();
                if (Geometry != null)
                    F.Shape = Geometry;

                int index = -1;

                F.Store();

                WSE.StopEditOperation();
                WSE.StopEditing(true);

                return null;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
Esempio n. 27
0
        public void CopyAnnotationFeatures()
        {
            try
            {
                IMxDocument pMxDoc      = (IMxDocument)ArcMap.Application.Document;
                IMap        pMap        = pMxDoc.FocusMap;
                ILayer      SourceLayer = pMap.Layer[0];
                ILayer      TargetLayer = pMap.Layer[1];

                IFeatureLayer SourceFLayer = (IFeatureLayer)SourceLayer;
                IFeatureLayer TargetFLayer = (IFeatureLayer)TargetLayer;

                IFeatureClass SourceFeatureClass = SourceFLayer.FeatureClass;
                IFeatureClass TargetFeatureClass = TargetFLayer.FeatureClass;

                IFields TargetFields = TargetFeatureClass.Fields;
                IFields SourceFields = SourceFeatureClass.Fields;

                IDictionary <int, int> symbSourceTargIdXref = new Dictionary <int, int>();
                symbSourceTargIdXref.Add(4, 17);
                symbSourceTargIdXref.Add(5, 22);
                symbSourceTargIdXref.Add(43, 45);
                symbSourceTargIdXref.Add(45, 45);
                ISymbolCollection targetSymbolsColl = (TargetFeatureClass.Extension as IAnnoClass).SymbolCollection;

                IField pFld;

                int[] lSrcFlds;
                int[] lTarFlds;

                int lFld, lExFld, i;
                lExFld = 0;
                for (lFld = 0; lFld <= (SourceFields.FieldCount - 1); lFld++)
                {
                    pFld = SourceFields.Field[lFld];

                    if (pFld.Type != esriFieldType.esriFieldTypeOID && pFld.Type != esriFieldType.esriFieldTypeGeometry && pFld.Name.ToUpper() != "ELEMENT" && pFld.Name.ToUpper() != "ZORDER" && pFld.Editable == true)
                    {
                        lExFld = lExFld + 1;
                    }
                }


                lSrcFlds = new int[lExFld];
                lTarFlds = new int[lExFld];

                i = 0;

                for (lFld = 0; lFld <= (SourceFields.FieldCount - 1); lFld++)
                {
                    pFld = SourceFields.Field[lFld];
                    if (pFld.Type != esriFieldType.esriFieldTypeOID && pFld.Type != esriFieldType.esriFieldTypeGeometry && pFld.Name.ToUpper() != "ELEMENT" && pFld.Name.ToUpper() != "ZORDER" && pFld.Editable == true)
                    {
                        lSrcFlds[i] = lFld;
                        lTarFlds[i] = TargetFields.FindField(pFld.Name);
                        i           = i + 1;
                    }
                }


                IFeatureCursor pICursor;
                pICursor = SourceFeatureClass.Search(null, true);

                IFeature pIFeat;
                pIFeat = pICursor.NextFeature();

                IFDOGraphicsLayerFactory pGLF;
                pGLF = new FDOGraphicsLayerFactory();

                IDataset pDataset;
                pDataset = (IDataset)TargetFeatureClass;



                IAnnotationFeature pAnnoFeature;
                IClone             pAClone;
                IElement           pElement;


                IAnnoClass pTargetAnnoClass = (IAnnoClass)TargetFeatureClass.Extension;


                while (pIFeat != null)
                {
                    pAnnoFeature = (IAnnotationFeature)pIFeat;

                    if (pAnnoFeature.Annotation != null)
                    {
                        ITextElement sourceTextElement = pAnnoFeature.Annotation as ITextElement;
                        pAClone  = (IClone)sourceTextElement;
                        pElement = (IElement)pAClone.Clone();

                        ITextElement ptempTxt = (ITextElement)pAClone.Clone();
                        //set id
                        IFeature pTempFeat = TargetFeatureClass.CreateFeature();



                        ISymbolCollectionElement TargetSymbCollElem = (ISymbolCollectionElement)ptempTxt;

                        ISymbolCollectionElement sourceSymbCollElem = sourceTextElement as ISymbolCollectionElement;

                        int sourceSymbID = sourceSymbCollElem.SymbolID;

                        int symbolID = symbSourceTargIdXref[sourceSymbID];

                        ISymbolIdentifier2 pSymbI;
                        ISymbolCollection2 pSymbolColl2 = ( ISymbolCollection2 )pTargetAnnoClass.SymbolCollection;

                        pSymbolColl2.GetSymbolIdentifier(symbolID, out pSymbI);

                        //reset the desired symbol id

                        TargetSymbCollElem.set_SharedSymbol(pSymbI.ID, pSymbI.Symbol);


                        //save the annotation feature
                        IAnnotationFeature pAnnoFeat = (IAnnotationFeature)pTempFeat;

                        pAnnoFeat.Annotation = ptempTxt as IElement;
                        pTempFeat.Store();

                        //reset the over rided property by analysing the override code

                        if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideXOffset) <= sourceSymbCollElem.OverriddenProperties)
                        {
                            TargetSymbCollElem.XOffset = sourceSymbCollElem.XOffset;
                        }

                        if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideYOffset) <= sourceSymbCollElem.OverriddenProperties)
                        {
                            TargetSymbCollElem.YOffset = sourceSymbCollElem.YOffset;
                        }

                        if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideHorzAlignment) <= sourceSymbCollElem.OverriddenProperties)
                        {
                            TargetSymbCollElem.HorizontalAlignment = sourceSymbCollElem.HorizontalAlignment;
                        }

                        if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideVertAlignment) <= sourceSymbCollElem.OverriddenProperties)
                        {
                            TargetSymbCollElem.VerticalAlignment = sourceSymbCollElem.VerticalAlignment;
                        }

                        if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideFlipAngle) <= sourceSymbCollElem.OverriddenProperties)
                        {
                            TargetSymbCollElem.FlipAngle = TargetSymbCollElem.FlipAngle;
                        }

                        if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideSize) <= sourceSymbCollElem.OverriddenProperties)
                        {
                            TargetSymbCollElem.Size = sourceSymbCollElem.Size;
                        }

                        if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideColor) <= sourceSymbCollElem.OverriddenProperties)
                        {
                            TargetSymbCollElem.Color = sourceSymbCollElem.Color;
                        }

                        if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideCharSpacing) <= sourceSymbCollElem.OverriddenProperties)
                        {
                            TargetSymbCollElem.CharacterSpacing = sourceSymbCollElem.CharacterSpacing;
                        }

                        if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideCharWidth) <= sourceSymbCollElem.OverriddenProperties)
                        {
                            TargetSymbCollElem.CharacterWidth = sourceSymbCollElem.CharacterWidth;
                        }

                        if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideWordSpacing) <= sourceSymbCollElem.OverriddenProperties)
                        {
                            TargetSymbCollElem.WordSpacing = sourceSymbCollElem.WordSpacing;
                        }

                        if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideLeading) <= sourceSymbCollElem.OverriddenProperties)
                        {
                            TargetSymbCollElem.Leading = sourceSymbCollElem.Leading;
                        }

                        if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideBold) <= sourceSymbCollElem.OverriddenProperties)
                        {
                            TargetSymbCollElem.Bold = sourceSymbCollElem.Bold;
                        }
                        if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideItalic) <= sourceSymbCollElem.OverriddenProperties)
                        {
                            TargetSymbCollElem.Italic = sourceSymbCollElem.Italic;
                        }

                        if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideUnderline) <= sourceSymbCollElem.OverriddenProperties)
                        {
                            TargetSymbCollElem.Underline = sourceSymbCollElem.Underline;
                        }

                        if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideBackground) <= sourceSymbCollElem.OverriddenProperties)
                        {
                            TargetSymbCollElem.Background = sourceSymbCollElem.Background;
                        }

                        if ((sourceSymbCollElem.OverriddenProperties ^ (int)esriSymbolOverrideEnum.esriSymbolOverrideFontName) <= sourceSymbCollElem.OverriddenProperties)
                        {
                            TargetSymbCollElem.FontName = sourceSymbCollElem.FontName;
                        }

                        //save the feature again
                        pAnnoFeat.Annotation = ptempTxt as IElement;
                        pTempFeat.Store();
                    }
                    pIFeat = pICursor.NextFeature();
                }


                pMxDoc.UpdateContents();
                pMxDoc.ActiveView.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
 private bool insertRecords(IFeatureClass ftrCls, IFeature ftr, List<IGeometry> geoLst)
 {
     bool x = false;
     try
     {
         IFields flds = ftr.Fields;
         foreach (IGeometry geo in geoLst)
         {
             IFeature nFtr = ftrCls.CreateFeature();
             for (int f = 0; f < flds.FieldCount; f++)
             {
                 IField fld = flds.get_Field(f);
                 esriFieldType fldType = fld.Type;
                 int nFldIndex = nFtr.Fields.FindField(fld.Name);
                 if (fld.Editable==true && (fldType == esriFieldType.esriFieldTypeString || fldType == esriFieldType.esriFieldTypeSmallInteger || fldType == esriFieldType.esriFieldTypeSingle || fldType == esriFieldType.esriFieldTypeInteger || fldType == esriFieldType.esriFieldTypeDouble))
                 {
                     nFtr.set_Value(nFldIndex, ftr.get_Value(f));
                     if (fld.Name == "Shape_Area")
                     {
                         nFtr.set_Value(nFtr.Fields.FindField("Shape_Area"),((IArea)geo).Area);
                     }
                 }
             }
             nFtr.Shape = geo;
             nFtr.Store();
         }
         x = true;
     }
     catch (Exception e)
     {
         x = false;
         Console.WriteLine(e.ToString());
     }
     return x;
 }
Esempio n. 29
0
        /// <summary>
        /// 创建地理要素
        /// </summary>
        /// <param name="pGeom"></param>
        /// <param name="pMap"></param>
        /// <param name="pCurrentLayer"></param>
        public static void CreateFeature(IGeometry pGeom, IMap pMap, IFeatureClass pFeatureClass)
        {
            if (pGeom != null)
            {
                IDataset       pDataset;
                IWorkspaceEdit pWorkspaceEdit;

                if (pFeatureClass == null)
                {
                    return;
                }

                pDataset = (IDataset)pFeatureClass;

                pWorkspaceEdit = (IWorkspaceEdit)pDataset.Workspace;
                int          index = pFeatureClass.FindField(pFeatureClass.ShapeFieldName);
                IGeometryDef pGD   = pFeatureClass.Fields.get_Field(index).GeometryDef;
                if (pGD.HasZ)
                {
                    IZAware pZA = (IZAware)pGeom;
                    pZA.ZAware = true;
                    IZ     pZ = pGeom as IZ;
                    double zmin = -1000, zmax = 1000;
                    if (pGD.SpatialReference.HasZPrecision())
                    {
                        pGD.SpatialReference.GetZDomain(out zmin, out zmax);
                    }
                    if (pZ != null)
                    {
                        //pZ.SetConstantZ(zmin);
                        pZ.SetConstantZ(0);
                    }
                    else
                    {
                        IPoint p = (pGeom as IPoint);
                        if (p != null)
                        {
                            if (p.Z.ToString() == "非数字")
                            {
                                //p.Z = zmin;
                                p.Z = 0;
                            }
                        }
                    }
                }

                if (pGD.HasM)
                {
                    IMAware pMA = (IMAware)pGeom;
                    pMA.MAware = true;
                }

                if (!pWorkspaceEdit.IsBeingEdited())
                {
                    pWorkspaceEdit.StartEditing(true);
                    pWorkspaceEdit.StartEditOperation();
                }

                IFeature pFeature;
                pFeature = pFeatureClass.CreateFeature();

                try
                {
                    pFeature.Shape = pGeom;
                    pFeature.Store();
                }
                catch (System.Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message);
                }

                if (pWorkspaceEdit.IsBeingEdited())
                {
                    pWorkspaceEdit.StopEditOperation();
                    pWorkspaceEdit.StopEditing(true);
                }

                pMap.ClearSelection();  //清除所有选择
            }
        }
 private void createFeatureClass()
 {
     string ftClsPath = rsUtil.TempMosaicDir+"\\catBnd.shp";
     IFields flds = new FieldsClass();
     IFieldsEdit fldsE = (IFieldsEdit)flds;
     IField fld = new FieldClass();
     IFieldEdit fldE = (IFieldEdit)fld;
     fldE.Name_2 = "catIndex";
     fldE.Type_2 = esriFieldType.esriFieldTypeSmallInteger;
     fldsE.AddField(fldE);
     ftCls = geoUtil.createFeatureClass(ftClsPath, fldsE, esriGeometryType.esriGeometryPolygon, sr);
     int catInd = ftCls.FindField("catIndex");
     int cnt = 0;
     foreach (IRaster rs in inrs)
     {
         IFeature ftr = ftCls.CreateFeature();
         ftr.set_Value(catInd, cnt);
         IEnvelope ext = ((IRasterProps)rs).Extent;
         IPolygon poly = new PolygonClass();
         IPointCollection pColl = (IPointCollection)poly;
         pColl.AddPoint(ext.UpperLeft);
         pColl.AddPoint(ext.UpperRight);
         pColl.AddPoint(ext.LowerRight);
         pColl.AddPoint(ext.LowerLeft);
         poly.Close();
         ftr.Shape = poly;
         ftr.Store();
         cnt++;
     }
 }
Esempio n. 31
0
        /// <summary>
        /// Creates the output featureclass, either fgdb featureclass or a shapefile
        /// </summary>
        /// <param name="outputPath">location of featureclass</param>
        /// <param name="saveAsType">Type of output selected, either fgdb featureclass or shapefile</param>
        /// <param name="graphicsList">List of graphics for selected tab</param>
        /// <param name="ipSpatialRef">Spatial Reference being used</param>
        /// <returns>Output featureclass</returns>
        public IFeatureClass CreateFCOutput(string outputPath, SaveAsType saveAsType, List <Graphic> graphicsList, ISpatialReference ipSpatialRef)
        {
            string        fcName     = System.IO.Path.GetFileName(outputPath);
            string        folderName = System.IO.Path.GetDirectoryName(outputPath);
            IFeatureClass fc         = null;

            try
            {
                bool isGraphicLineOrRangeRing = graphicsList[0].GraphicType == GraphicTypes.Line || graphicsList[0].GraphicType == GraphicTypes.RangeRing;
                if (saveAsType == SaveAsType.FileGDB)
                {
                    IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactory();
                    IWorkspace        workspace        = workspaceFactory.OpenFromFile(folderName, 0);
                    IFeatureWorkspace fWorkspace       = (IFeatureWorkspace)workspace;

                    if (DoesFeatureClassExist(folderName, fcName))
                    {
                        DeleteFeatureClass(fWorkspace, fcName);
                    }

                    fc = CreateFeatureClass(fWorkspace, fcName, graphicsList, isGraphicLineOrRangeRing);

                    foreach (Graphic graphic in graphicsList)
                    {
                        if (graphic.Attributes == null)
                        {
                            continue;
                        }
                        IFeature feature = fc.CreateFeature();

                        if (graphic.GraphicType != GraphicTypes.Line && graphic.GraphicType != GraphicTypes.RangeRing)
                        {
                            feature.Shape = PolylineToPolygon(graphic.Geometry);
                        }
                        else
                        {
                            feature.Shape = graphic.Geometry;
                        }

                        switch (graphic.GraphicType.ToString())
                        {
                        case "Line":
                        {
                            System.Object dist;
                            System.Object angle;
                            System.Object angleunit;
                            System.Object ox;
                            System.Object oy;
                            System.Object dx;
                            System.Object dy;
                            System.Object distunit;

                            graphic.Attributes.TryGetValue("distance", out dist);
                            graphic.Attributes.TryGetValue("distanceunit", out distunit);
                            graphic.Attributes.TryGetValue("startx", out ox);
                            graphic.Attributes.TryGetValue("starty", out oy);
                            graphic.Attributes.TryGetValue("endx", out dx);
                            graphic.Attributes.TryGetValue("endy", out dy);
                            graphic.Attributes.TryGetValue("angle", out angle);
                            graphic.Attributes.TryGetValue("angleunit", out angleunit);
                            feature.set_Value(feature.Fields.FindField("Distance"), dist);
                            feature.set_Value(feature.Fields.FindField("DistanceUnit"), distunit);
                            feature.set_Value(feature.Fields.FindField("OriginX"), ox);
                            feature.set_Value(feature.Fields.FindField("OriginY"), oy);
                            feature.set_Value(feature.Fields.FindField("DestinationX"), dx);
                            feature.set_Value(feature.Fields.FindField("DestinationY"), dy);
                            feature.set_Value(feature.Fields.FindField("Angle"), angle);
                            feature.set_Value(feature.Fields.FindField("AngleUnit"), angleunit);
                            feature.Store();
                            break;
                        }

                        case "Circle":
                        {
                            System.Object radius;
                            System.Object disttype;
                            System.Object distunit;
                            System.Object centerx;
                            System.Object centery;

                            graphic.Attributes.TryGetValue("radius", out radius);
                            graphic.Attributes.TryGetValue("distanceunit", out distunit);
                            graphic.Attributes.TryGetValue("disttype", out disttype);
                            graphic.Attributes.TryGetValue("centerx", out centerx);
                            graphic.Attributes.TryGetValue("centery", out centery);

                            feature.set_Value(feature.Fields.FindField("Distance"), radius);
                            feature.set_Value(feature.Fields.FindField("DistanceUnit"), distunit);
                            feature.set_Value(feature.Fields.FindField("DistanceType"), disttype);
                            feature.set_Value(feature.Fields.FindField("CenterX"), centerx);
                            feature.set_Value(feature.Fields.FindField("CenterY"), centery);

                            feature.Store();
                            break;
                        }

                        case "Ellipse":
                        {
                            System.Object majoraxis;
                            System.Object minoraxis;
                            System.Object angle;
                            System.Object distunit;
                            System.Object centerx;
                            System.Object centery;
                            System.Object angleunit;

                            graphic.Attributes.TryGetValue("majoraxis", out majoraxis);
                            graphic.Attributes.TryGetValue("minoraxis", out minoraxis);
                            graphic.Attributes.TryGetValue("azimuth", out angle);
                            graphic.Attributes.TryGetValue("distanceunit", out distunit);
                            graphic.Attributes.TryGetValue("centerx", out centerx);
                            graphic.Attributes.TryGetValue("centery", out centery);
                            graphic.Attributes.TryGetValue("angleunit", out angleunit);

                            feature.set_Value(feature.Fields.FindField("MajorAxis"), majoraxis);
                            feature.set_Value(feature.Fields.FindField("MinorAxis"), minoraxis);
                            feature.set_Value(feature.Fields.FindField("DistanceUnit"), distunit);
                            feature.set_Value(feature.Fields.FindField("Angle"), angle);
                            feature.set_Value(feature.Fields.FindField("CenterX"), centerx);
                            feature.set_Value(feature.Fields.FindField("CenterY"), centery);
                            feature.set_Value(feature.Fields.FindField("AngleUnit"), angleunit);

                            feature.Store();
                            break;
                        }

                        case "RangeRing":
                        {
                            System.Object rings;
                            System.Object distance;
                            System.Object radials;
                            System.Object distunit;
                            System.Object centerx;
                            System.Object centery;

                            graphic.Attributes.TryGetValue("rings", out rings);
                            graphic.Attributes.TryGetValue("distance", out distance);
                            graphic.Attributes.TryGetValue("radials", out radials);
                            graphic.Attributes.TryGetValue("distanceunit", out distunit);
                            graphic.Attributes.TryGetValue("centerx", out centerx);
                            graphic.Attributes.TryGetValue("centery", out centery);

                            feature.set_Value(feature.Fields.FindField("Rings"), rings);
                            feature.set_Value(feature.Fields.FindField("Distance"), distance);
                            feature.set_Value(feature.Fields.FindField("Radials"), radials);
                            feature.set_Value(feature.Fields.FindField("DistanceUnit"), distunit);
                            feature.set_Value(feature.Fields.FindField("CenterX"), centerx);
                            feature.set_Value(feature.Fields.FindField("CenterY"), centery);
                            feature.Store();
                            break;
                        }
                        }
                    }
                }
                else if (saveAsType == SaveAsType.Shapefile)
                {
                    // already asked them for confirmation to overwrite file
                    if (File.Exists(outputPath))
                    {
                        DeleteShapeFile(outputPath);
                    }

                    fc = ExportToShapefile(outputPath, graphicsList, ipSpatialRef, isGraphicLineOrRangeRing);
                }
                return(fc);
            }
            catch (Exception ex)
            {
                return(fc);
            }
        }
Esempio n. 32
0
        // FeatureDataTablet to shapefile
        private void WriteFeatureDataTable2shp(GeometryType gtype, FeatureDataTable ftable, IFeatureClass fc, String shapefilePath)
        {
            int rowCount = ftable.Rows.Count;
            int colCount = ftable.Columns.Count;
            int geometryColIndex = ftable.GeometryColumnIndex;
            //GeometryType gtype = selLayer.GeometryType;
            toolStripProgressBar1.Maximum = rowCount;
            toolStripProgressBar1.Value = 0;
            toolStripProgressBar1.Visible = true;

            // for each selected features
            for (int i = 0; i < rowCount; i++)
            {
                toolStripProgressBar1.Value = i + 1;
                selectionStripStatusLabel1.Text = toolStripProgressBar1.Value.ToString() + "/" + rowCount.ToString() + " features exported .";
                toolStripStatusLabel2.Text = shapefilePath;
                Application.DoEvents();

                // create a new feature
                IFeature feature = fc.CreateFeature();
                DataRow arow = ftable.Rows[i];
                string globalid;
                if (arow.Table.Columns.Contains("GlobalID"))
                {
                    globalid = arow["GlobalID"].ToString();
                }
                else
                {
                    globalid = arow["OBJECTID"].ToString();
                }

                // geometry
                ESRI.ArcGIS.Mobile.Geometries.Geometry mobileGeometry = arow[geometryColIndex] as ESRI.ArcGIS.Mobile.Geometries.Geometry;
                byte[] mobileGeometryByteArray = mobileGeometry.ExportToEsriShape();
                int len = mobileGeometryByteArray.Length;
                switch (gtype)
                {
                    case GeometryType.Point:
                        ESRI.ArcGIS.Geometry.IPoint aoShape = new ESRI.ArcGIS.Geometry.PointClass();
                        ((ESRI.ArcGIS.Geometry.IESRIShape)aoShape).ImportFromESRIShape(ref len, ref mobileGeometryByteArray[0]);
                        feature.Shape = aoShape;
                        break;

                    case GeometryType.Multipoint:
                        ESRI.ArcGIS.Geometry.IMultipoint aoShape2 = new ESRI.ArcGIS.Geometry.MultipointClass();
                        ((ESRI.ArcGIS.Geometry.IESRIShape)aoShape2).ImportFromESRIShape(ref len, ref mobileGeometryByteArray[0]);
                        feature.Shape = aoShape2;
                        break;

                    case GeometryType.Polyline:
                        ESRI.ArcGIS.Geometry.IPolyline aoShape3 = new ESRI.ArcGIS.Geometry.PolylineClass();
                        ((ESRI.ArcGIS.Geometry.IESRIShape)aoShape3).ImportFromESRIShape(ref len, ref mobileGeometryByteArray[0]);
                        feature.Shape = aoShape3;
                        break;

                    case GeometryType.Polygon:
                        ESRI.ArcGIS.Geometry.IPolygon aoShape4 = new ESRI.ArcGIS.Geometry.PolygonClass();
                        ((ESRI.ArcGIS.Geometry.IESRIShape)aoShape4).ImportFromESRIShape(ref len, ref mobileGeometryByteArray[0]);
                        feature.Shape = aoShape4;
                        break;
                }

                // insert other attributes
                // in mobile cache, the last col is for geometry
                // in shapefile, fid and shape fields are first two, for other fields index = +2
                for (int col = 0; col < colCount - 1; col++)
                {
                    // type
                    DataColumn dc = ftable.Columns[col];
                    Type dt = dc.DataType;

                    // guid or globalid, change to string
                    if (dt == typeof(Guid) || (dt == typeof(ESRI.ArcGIS.Mobile.GlobalId)))
                    {
                        feature.set_Value(col + 2, arow[col].ToString());
                        //feature.Store();
                        continue;
                    }

                    // if blob field, write to file
                    if (dt == typeof(Byte[]))
                    {
                        continue;
                    }
                    // raster field, write to jpg files
                    if (dt == typeof(Bitmap))
                    {
                        string photofoldername = shapefilePath + "\\" + dc.ColumnName;
                        if (!Directory.Exists(photofoldername))
                            continue;

                        // get bitmap from a raster field, save to ImageSource
                        System.Windows.Media.ImageSource imgsrc = null;
                        Bitmap bitmap = arow[col] as Bitmap;
                        if (bitmap == null)
                            continue;

                        System.Windows.Int32Rect rect = new System.Windows.Int32Rect(0, 0, bitmap.Width, bitmap.Height);
                        IntPtr hBitmap = IntPtr.Zero;
                        try
                        {
                            hBitmap = bitmap.GetHbitmap();
                            imgsrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                                     hBitmap, IntPtr.Zero, rect, BitmapSizeOptions.FromEmptyOptions());

                            // write the ImageSource to jpg
                            if (imgsrc == null)
                                continue;
                            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                            encoder.Frames.Add(BitmapFrame.Create(imgsrc as BitmapSource));
                            string fileName = photofoldername + "\\" + globalid + ".jpg";
                            using (System.IO.FileStream file = File.OpenWrite(fileName))
                            {
                                encoder.Save(file);
                            }

                            continue;

                        }
                        finally
                        {
                            if (hBitmap != IntPtr.Zero)
                                DeleteObject(hBitmap);
                        }
                    }  // end of bitmap

                    // other data types, just set the value
                    if (arow[col].ToString() != "")
                        feature.set_Value(col + 2, arow[col]);
                    else
                        feature.set_Value(col + 2, 0);

                }

                feature.Store();
            }

            //MessageBox.Show(rowCount.ToString() + " features saved into a shapefile at: " + shapefilePath);
            toolStripProgressBar1.Value = 0;
            selectionStripStatusLabel1.Text = "";
            toolStripProgressBar1.Visible = false;

            return;
        }
Esempio n. 33
0
        /// <summary>
        /// Export graphics to a shapefile
        /// </summary>
        /// <param name="fileNamePath">Path to shapefile</param>
        /// <param name="graphicsList">List of graphics for selected tab</param>
        /// <param name="ipSpatialRef">Spatial Reference being used</param>
        /// <returns>Created featureclass</returns>
        private IFeatureClass ExportToShapefile(string fileNamePath, List <Graphic> graphicsList, ISpatialReference ipSpatialRef, bool polyLineFC)
        {
            int           index           = fileNamePath.LastIndexOf('\\');
            string        folder          = fileNamePath.Substring(0, index);
            string        nameOfShapeFile = fileNamePath.Substring(index + 1);
            string        shapeFieldName  = "Shape";
            IFeatureClass featClass       = null;

            using (ComReleaser oComReleaser = new ComReleaser())
            {
                try
                {
                    IWorkspaceFactory workspaceFactory = null;
                    workspaceFactory = new ShapefileWorkspaceFactoryClass();
                    IWorkspace        workspace        = workspaceFactory.OpenFromFile(folder, 0);
                    IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace;
                    IFields           fields           = null;
                    IFieldsEdit       fieldsEdit       = null;
                    fields     = new Fields();
                    fieldsEdit = (IFieldsEdit)fields;
                    IField     field     = null;
                    IFieldEdit fieldEdit = null;
                    field            = new FieldClass();///###########
                    fieldEdit        = (IFieldEdit)field;
                    fieldEdit.Name_2 = "Shape";
                    fieldEdit.Type_2 = (esriFieldType.esriFieldTypeGeometry);
                    IGeometryDef     geomDef     = null;
                    IGeometryDefEdit geomDefEdit = null;
                    geomDef     = new GeometryDefClass();///#########
                    geomDefEdit = (IGeometryDefEdit)geomDef;

                    if (polyLineFC)
                    {
                        geomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline;
                    }
                    else
                    {
                        geomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
                    }

                    geomDefEdit.SpatialReference_2 = ipSpatialRef;

                    fieldEdit.GeometryDef_2 = geomDef;
                    fieldsEdit.AddField(field);
                    string graphicsType = graphicsList[0].GraphicType.ToString();
                    switch (graphicsType)
                    {
                    case "Line":
                    {
                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "Distance";
                        fieldEdit.AliasName_2 = "Geodetic Distance";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "DistUnit";
                        fieldEdit.AliasName_2 = "Distance Unit";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "OriginX";
                        fieldEdit.AliasName_2 = "Origin X";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "OriginY";
                        fieldEdit.AliasName_2 = "Origin Y";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "DestX";
                        fieldEdit.AliasName_2 = "Dest X";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "DestY";
                        fieldEdit.AliasName_2 = "Dest Y";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "Angle";
                        fieldEdit.AliasName_2 = "Angle";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "AngleUnit";
                        fieldEdit.AliasName_2 = "Angle Unit";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                        fieldsEdit.AddField(field);

                        break;
                    }

                    case "Circle":
                    {
                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "Distance";
                        fieldEdit.AliasName_2 = "Distance";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "DistUnit";
                        fieldEdit.AliasName_2 = "Distance Unit";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "DistType";
                        fieldEdit.AliasName_2 = "Distance Type";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "CenterX";
                        fieldEdit.AliasName_2 = "Center X";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "CenterY";
                        fieldEdit.AliasName_2 = "Center Y";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        break;
                    }

                    case "Ellipse":
                    {
                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "MajAxis";
                        fieldEdit.AliasName_2 = "Major Axis";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "MinAxis";
                        fieldEdit.AliasName_2 = "Minor Axis";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "DistUnit";
                        fieldEdit.AliasName_2 = "Distance Unit";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "CenterX";
                        fieldEdit.AliasName_2 = "Center X";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "CenterY";
                        fieldEdit.AliasName_2 = "Center Y";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "Angle";
                        fieldEdit.AliasName_2 = "Angle";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "AngleUnit";
                        fieldEdit.AliasName_2 = "Angle Unit";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                        fieldsEdit.AddField(field);

                        break;
                    }

                    case "RangeRing":
                    {
                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "Rings";
                        fieldEdit.AliasName_2 = "Rings";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeInteger;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "Distance";
                        fieldEdit.AliasName_2 = "Geodetic Distance";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "DistUnit";
                        fieldEdit.AliasName_2 = "Distance Unit";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "Radials";
                        fieldEdit.AliasName_2 = "Radials";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeInteger;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "CenterX";
                        fieldEdit.AliasName_2 = "Center X";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        field                 = new FieldClass();
                        fieldEdit             = (IFieldEdit)field;
                        fieldEdit.Name_2      = "CenterY";
                        fieldEdit.AliasName_2 = "Center Y";
                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeDouble;
                        fieldsEdit.AddField(field);

                        break;
                    }
                    }

                    featClass = featureWorkspace.CreateFeatureClass(nameOfShapeFile, fields, null, null, esriFeatureType.esriFTSimple, shapeFieldName, "");

                    foreach (Graphic graphic in graphicsList)
                    {
                        if (graphic.Attributes == null)
                        {
                            continue;
                        }
                        IFeature feature = featClass.CreateFeature();

                        if (polyLineFC)
                        {
                            feature.Shape = graphic.Geometry;
                        }
                        else
                        {
                            feature.Shape = PolylineToPolygon(graphic.Geometry);
                        }
                        switch (graphic.GraphicType.ToString())
                        {
                        case "Line":
                        {
                            System.Object dist;
                            System.Object angle;
                            System.Object angleunit;
                            System.Object ox;
                            System.Object oy;
                            System.Object dx;
                            System.Object dy;
                            System.Object distunit;

                            graphic.Attributes.TryGetValue("distance", out dist);
                            graphic.Attributes.TryGetValue("distanceunit", out distunit);
                            graphic.Attributes.TryGetValue("startx", out ox);
                            graphic.Attributes.TryGetValue("starty", out oy);
                            graphic.Attributes.TryGetValue("endx", out dx);
                            graphic.Attributes.TryGetValue("endy", out dy);
                            graphic.Attributes.TryGetValue("angle", out angle);
                            graphic.Attributes.TryGetValue("angleunit", out angleunit);
                            feature.set_Value(feature.Fields.FindField("Distance"), dist);
                            feature.set_Value(feature.Fields.FindField("DistUnit"), distunit);
                            feature.set_Value(feature.Fields.FindField("OriginX"), ox);
                            feature.set_Value(feature.Fields.FindField("OriginY"), oy);
                            feature.set_Value(feature.Fields.FindField("DestX"), dx);
                            feature.set_Value(feature.Fields.FindField("DestY"), dy);
                            feature.set_Value(feature.Fields.FindField("Angle"), angle);
                            feature.set_Value(feature.Fields.FindField("AngleUnit"), angleunit);
                            break;
                        }

                        case "Circle":
                        {
                            System.Object radius;
                            System.Object disttype;
                            System.Object distunit;
                            System.Object centerx;
                            System.Object centery;

                            graphic.Attributes.TryGetValue("radius", out radius);
                            graphic.Attributes.TryGetValue("distanceunit", out distunit);
                            graphic.Attributes.TryGetValue("disttype", out disttype);
                            graphic.Attributes.TryGetValue("centerx", out centerx);
                            graphic.Attributes.TryGetValue("centery", out centery);

                            feature.set_Value(feature.Fields.FindField("Distance"), radius);
                            feature.set_Value(feature.Fields.FindField("DistUnit"), distunit);
                            feature.set_Value(feature.Fields.FindField("DistType"), disttype);
                            feature.set_Value(feature.Fields.FindField("CenterX"), centerx);
                            feature.set_Value(feature.Fields.FindField("CenterY"), centery);

                            break;
                        }

                        case "Ellipse":
                        {
                            System.Object majoraxis;
                            System.Object minoraxis;
                            System.Object angle;
                            System.Object distunit;
                            System.Object centerx;
                            System.Object centery;
                            System.Object angleunit;

                            graphic.Attributes.TryGetValue("majoraxis", out majoraxis);
                            graphic.Attributes.TryGetValue("minoraxis", out minoraxis);
                            graphic.Attributes.TryGetValue("azimuth", out angle);
                            graphic.Attributes.TryGetValue("distanceunit", out distunit);
                            graphic.Attributes.TryGetValue("centerx", out centerx);
                            graphic.Attributes.TryGetValue("centery", out centery);
                            graphic.Attributes.TryGetValue("angleunit", out angleunit);

                            feature.set_Value(feature.Fields.FindField("MajAxis"), majoraxis);
                            feature.set_Value(feature.Fields.FindField("MinAxis"), minoraxis);
                            feature.set_Value(feature.Fields.FindField("DistUnit"), distunit);
                            feature.set_Value(feature.Fields.FindField("Angle"), angle);
                            feature.set_Value(feature.Fields.FindField("CenterX"), centerx);
                            feature.set_Value(feature.Fields.FindField("CenterY"), centery);
                            feature.set_Value(feature.Fields.FindField("AngleUnit"), angleunit);
                            break;
                        }

                        case "RangeRing":
                        {
                            System.Object rings;
                            System.Object distance;
                            System.Object radials;
                            System.Object distunit;
                            System.Object centerx;
                            System.Object centery;

                            graphic.Attributes.TryGetValue("rings", out rings);
                            graphic.Attributes.TryGetValue("distance", out distance);
                            graphic.Attributes.TryGetValue("radials", out radials);
                            graphic.Attributes.TryGetValue("distanceunit", out distunit);
                            graphic.Attributes.TryGetValue("centerx", out centerx);
                            graphic.Attributes.TryGetValue("centery", out centery);

                            feature.set_Value(feature.Fields.FindField("Rings"), rings);
                            feature.set_Value(feature.Fields.FindField("Distance"), distance);
                            feature.set_Value(feature.Fields.FindField("Radials"), radials);
                            feature.set_Value(feature.Fields.FindField("DistUnit"), distunit);
                            feature.set_Value(feature.Fields.FindField("CenterX"), centerx);
                            feature.set_Value(feature.Fields.FindField("CenterY"), centery);
                            break;
                        }
                        }
                        feature.Store();
                    }

                    IFeatureLayer featurelayer = null;
                    featurelayer = new FeatureLayerClass();
                    featurelayer.FeatureClass = featClass;
                    featurelayer.Name         = featClass.AliasName;

                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workspace);
                    workspace = null;
                    GC.Collect();

                    return(featClass);
                }
                catch (Exception ex)
                {
                    return(featClass);
                }
            }
        }
Esempio n. 34
0
        /// <summary>
        /// ���ݼ���ͼ�������Ҫ��
        /// </summary>
        /// <params name="featureLayer">��ǰ�༭ͼ��</params>
        /// <params name="geom">Ҫ�ؼ���</params>
        public static void CreateFeature(IFeatureClass featureClass, IGeometryArray geometryArray2, List<ziduan> list)
        {
            IWorkspaceEdit workspaceEdit = null;
            IFeatureCursor featureCursor = null;

            try
            {
                IDataset dataset = (IDataset)featureClass;
                IWorkspace workspace = dataset.Workspace;
                workspaceEdit = workspace as IWorkspaceEdit;

                workspaceEdit.StartEditing(true);
                workspaceEdit.StartEditOperation();
                for (int i = 0; i < geometryArray2.Count; i++)
                {
                    IFeature feature = featureClass.CreateFeature();
                    IGeometry mGeometry = geometryArray2.get_Element(i);
                    DataEditCommon.ZMValue(feature, mGeometry);     //����ͼ��Zֵ����
                    feature.Shape = mGeometry;
                    if (list != null)
                    {
                        for (int j = 0; j < list.Count; j++)
                        {
                            if (feature.Fields.FindField(list[j].name) > 0)
                            {
                                feature.set_Value(feature.Fields.FindField(list[j].name), list[j].value);
                            }
                        }
                    }
                    if (feature.Fields.FindField("id") > 0)
                    {
                        feature.set_Value(feature.Fields.FindField("id"), (i + 1).ToString());
                    }
                    if (feature.Fields.FindField("Contour") > 0)
                    {
                        feature.set_Value(feature.Fields.FindField("Contour"), feature.Shape.Envelope.ZMax);
                    }
                    feature.Store();
                }
                workspaceEdit.StopEditOperation();
                workspaceEdit.StopEditing(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                workspaceEdit.AbortEditOperation();
                workspaceEdit.StopEditing(false);
            }
            finally
            {
                if (featureCursor != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(featureCursor);  //�ͷ�ָ��
                }
            }
        }
Esempio n. 35
0
        private void AddElement(IPolyline polyline)
        {
            try
            {
                ArcGIS.Common.Editor.Editor.StartEditOperation();

                string strLineInfo = CommonHelper.GetIntersectInformationFlagLineOnlyOne(polyline, _cheQiConfig,
                                                                                         _feature);
                if (string.IsNullOrWhiteSpace(strLineInfo))
                {
                    MessageBox.Show(@"扯旗字段为空,请重新设置扯旗字段", @"扯旗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                IPoint referPoint = new PointClass();
                referPoint.X = _polyline.ToPoint.X;
                referPoint.Y = _polyline.ToPoint.Y;

                stdole.IFontDisp fontDisp = new StdFontClass() as IFontDisp;
                fontDisp.Name          = _cheQiConfig.FontName;
                fontDisp.Size          = _cheQiConfig.FontSize;
                fontDisp.Italic        = _cheQiConfig.Italic;
                fontDisp.Underline     = _cheQiConfig.Underline;
                fontDisp.Bold          = _cheQiConfig.Bold;
                fontDisp.Strikethrough = _cheQiConfig.Strikethrough;

                ITextSymbol textSymbol = new TextSymbolClass();
                textSymbol.Size  = (double)_cheQiConfig.FontSize;
                textSymbol.Font  = fontDisp;
                textSymbol.Color = _cheQiConfig.FontColor;
                textSymbol.HorizontalAlignment = esriTextHorizontalAlignment.esriTHALeft;

                ITextElement textElement = new TextElementClass();
                textElement.Text      = strLineInfo;
                textElement.Symbol    = textSymbol;
                textElement.ScaleText = true;

                IPoint textPoint = new PointClass();
                textPoint.X = referPoint.X;
                textPoint.Y = referPoint.Y + 1;

                IElement element = textElement as IElement;
                element.Geometry = textPoint;

                IFeature annoFeature = _cheQiConfig.FlagAnnoLayer.FeatureClass.CreateFeature();
                IAnnotationClassExtension annotationClassExtension = _cheQiConfig.FlagAnnoLayer.FeatureClass.Extension as IAnnotationClassExtension;
                IAnnotationFeature        annotationFeature        = new AnnotationFeatureClass();
                annotationFeature                 = annoFeature as IAnnotationFeature;
                annotationFeature.Annotation      = element;
                annotationFeature.LinkedFeatureID = _feature.OID;
                annoFeature.Store();
                _context.ActiveView.ScreenDisplay.StartDrawing(_context.ActiveView.ScreenDisplay.hDC, 0);
                annotationClassExtension.Draw(annotationFeature, _context.ActiveView.ScreenDisplay, null);
                _context.ActiveView.ScreenDisplay.FinishDrawing();

                double           maxLength            = annoFeature.Shape.Envelope.Width;
                IFeatureClass    flagLineFeatureClass = _cheQiConfig.FlagLineLayer.FeatureClass;
                IFeature         feature         = flagLineFeatureClass.CreateFeature();
                IPointCollection pointCollection = _polyline as IPointCollection;
                IPoint           point           = new PointClass();
                point.Y = referPoint.Y;
                point.X = referPoint.X + maxLength;
                pointCollection.AddPoint(point);
                feature.Shape = pointCollection as IPolyline;
                feature.Store();

                _context.ActiveView.Refresh();
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
            finally
            {
                ArcGIS.Common.Editor.Editor.StartEditOperation();
            }
        }
Esempio n. 36
0
 //向shp中添加要素  pPolygon多边形   pFeatureClass多边形shp
 public static void AddFeatureToFeatureClass(IPolygon pPolygon, IFeatureClass pFeatureClass)
 {
     IFeature pFeature = pFeatureClass.CreateFeature();
     pFeature.Shape = pPolygon;
     pFeature.Store();
 }
        //合并要素
        private void UnionFeatures(IEnumFeature selectedFeatures, IFeature pMergeFeature)
        {
            IFeature  feature  = null;
            IGeometry geometry = null;
            object    missing  = Type.Missing;

            selectedFeatures.Reset();
            feature = selectedFeatures.Next();
            if (feature == null)
            {
                return;
            }
            IFeatureClass       featureClass = feature.Class as IFeatureClass;
            IGeometryCollection geometries   = new GeometryBagClass();
            IDataset            dataset      = null;

            while (feature != null)
            {
                geometry = feature.ShapeCopy;
                geometries.AddGeometry(geometry, ref missing, ref missing);
                feature = selectedFeatures.Next();
            }
            ITopologicalOperator2 unionedGeometry = null;

            switch (featureClass.ShapeType)
            {
            case esriGeometryType.esriGeometryMultipoint:
                unionedGeometry = new MultipointClass(); break;

            case esriGeometryType.esriGeometryPolyline:
                unionedGeometry = new PolylineClass(); break;

            case esriGeometryType.esriGeometryPolygon:
                unionedGeometry = new PolygonClass(); break;

            default: break;
            }
            IEnumGeometry enuGeo = geometries as IEnumGeometry;

            unionedGeometry.ConstructUnion(enuGeo);
            ITopologicalOperator2 topo = unionedGeometry as ITopologicalOperator2;

            topo.IsKnownSimple_2 = false; topo.Simplify();
            IFeatureClass targetFeatureClass = currentLayer.FeatureClass;

            dataset = featureClass as IDataset;
            selectedFeatures.Reset();
            //如果没有IWorkspaceEdit则无法进行撤销重做操作
            IWorkspaceEdit workspaceEdit = dataset.Workspace as IWorkspaceEdit;

            try
            {
                //workspaceEdit.StartEditOperation();
                IFeature    unionedFeature = targetFeatureClass.CreateFeature();
                IFields     pFields        = unionedFeature.Fields;
                IFieldsEdit pFieldsEdit    = pFields as IFieldsEdit;
                IField      pField         = null;
                for (int i = 0; i < pFields.FieldCount; i++)
                {
                    pField = pFields.Field[i];
                    if (targetFeatureClass.AreaField != null && targetFeatureClass.LengthField != null)
                    {
                        if (pField.Name != targetFeatureClass.OIDFieldName && pField.Name != targetFeatureClass.ShapeFieldName &&
                            pField.Name != targetFeatureClass.AreaField.Name && pField.Name != targetFeatureClass.LengthField.Name)
                        {
                            unionedFeature.set_Value(i, pMergeFeature.Value[i]);
                        }
                    }
                    else
                    {
                        if (pField.Name != targetFeatureClass.OIDFieldName && pField.Name != targetFeatureClass.ShapeFieldName)
                        {
                            unionedFeature.set_Value(i, pMergeFeature.Value[i]);
                        }
                    }
                }

                unionedFeature.Shape = unionedGeometry as IGeometry;
                unionedFeature.Store();
                while ((feature = selectedFeatures.Next()) != null)
                {
                    feature.Delete();
                }
                workspaceEdit.StopEditOperation();
            }
            catch (Exception ex)
            {
                //SysLogHelper.WriteOperationLog("要素合并错误", ex.Source, "数据编辑");
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 38
0
        private void appendParcelField(IFeatureClass parcelFC)
        {
            if (perceel == null) return;

            IFeatureCursor insertCursor = parcelFC.Insert(false);

            datacontract.geojsonPolygon jsPoly = JsonConvert.DeserializeObject<datacontract.geojsonPolygon>(perceel.geometry.shape);
            IPolygon lbShape = geopuntHelper.geojson2esriPolygon( jsPoly , (int)dataHandler.CRS.Lambert72 );
            IPolygon mapShape = (IPolygon)geopuntHelper.Transform(lbShape, map.SpatialReference);

            IFeature feature = parcelFC.CreateFeature();
            feature.Shape = (IGeometry)mapShape;

            int capakeyIdx = parcelFC.FindField("capakey");
            feature.set_Value(capakeyIdx, perceel.capakey);

            int perceelnrIdx = parcelFC.FindField("perceelnr");
            feature.set_Value(perceelnrIdx, perceel.perceelnummer);

            int grondnrIdx = parcelFC.FindField("grondnr");
            feature.set_Value(grondnrIdx, perceel.grondnummer);

            int exponentIdx = parcelFC.FindField("exponent");
            feature.set_Value(exponentIdx, perceel.exponent);

            int machtIdx = parcelFC.FindField("macht");
            feature.set_Value(machtIdx, perceel.macht);

            int bisnrIdx = parcelFC.FindField("bisnr");
            feature.set_Value(bisnrIdx, perceel.bisnummer);

            int perceeltypeIdx = parcelFC.FindField("type");
            feature.set_Value(perceeltypeIdx, perceel.type);

            string adres = string.Join("-", perceel.adres.ToArray()) ;
            if (adres.Length > 254)
                adres = adres.Substring(0, 254);

            int adresIdx = parcelFC.FindField("adres");
            feature.set_Value(adresIdx, adres);

            feature.Store();
        }
Esempio n. 39
0
        /// <summary>
        /// _pFtClass参数为Stops的要素类,_pPointC是用鼠标点的点生成的点的集合,最后一个参数是捕捉距离
        /// </summary>
        /// <param name="_pNaContext"></param>
        /// <param name="_pFtClass"></param>
        /// <param name="_pPointC"></param>
        /// <param name="_pDist"></param>
        void NASolve(INAContext _pNaContext,IFeatureClass _pFtClass, IPointCollection _pPointC, double _pDist)
        {
            INALocator pNAlocator = _pNaContext.Locator;
            for (int i = 0; i < _pPointC.PointCount; i++)
            {
                IFeature pFt = _pFtClass.CreateFeature();

                IRowSubtypes pRowSubtypes = pFt as IRowSubtypes;

                pRowSubtypes.InitDefaultValues();

                pFt.Shape = _pPointC.get_Point(i) as IGeometry;

                IPoint pPoint = null;

                 INALocation pNalocation = null;

                pNAlocator.QueryLocationByPoint(_pPointC .get_Point(i),ref pNalocation,ref pPoint,ref _pDist);

                INALocationObject pNAobject = pFt as INALocationObject;

                pNAobject.NALocation = pNalocation;

                int pNameFieldIndex = _pFtClass.FindField("Name");

                pFt.set_Value(pNameFieldIndex, pPoint.X.ToString() + "," + pPoint.Y.ToString());

                int pStatusFieldIndex = _pFtClass.FindField("Status");

                pFt.set_Value(pStatusFieldIndex, esriNAObjectStatus.esriNAObjectStatusOK);

                int pSequenceFieldIndex = _pFtClass.FindField("Sequence");

                pFt.set_Value(_pFtClass.FindField("Sequence"), ((ITable)_pFtClass).RowCount(null));

                pFt.Store();

            }
        }